Php valid email preg_match
A classic!
In PHP, you can use the preg_match
function to validate an email address using a regular expression. Here's a common pattern:
$pattern = '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/';
$email = '[email protected]';
if (preg_match($pattern, $email)) {
echo 'Valid email address!';
} else {
echo 'Invalid email address!';
}
Let's break down the pattern:
^
matches the start of the string[a-zA-Z0-9._%+-]+
matches one or more of the following characters: letters (both uppercase and lowercase), numbers, dot (.), hyphen (-), underscore (_), percent (%), plus sign (+)@
matches the @ symbol[a-zA-Z0-9.-]+
matches one or more of the following characters: letters (both uppercase and lowercase), numbers, dot (.), hyphen (-)\.
matches a period (.) character[a-zA-Z]{2,}
matches the domain extension (it must be at least 2 characters long and only contain letters)$
matches the end of the string
This pattern is not foolproof, as it's possible to create invalid email addresses that still match this pattern. However, it's a good starting point for most use cases.
If you want to make it more robust, you can add additional checks, such as:
- Checking for a maximum length (e.g., 254 characters)
- Verifying the presence of a local part (before the @ symbol)
- Checking for a valid top-level domain (TLD)
Here's an updated pattern:
$pattern = '/^(?:[a-zA-Z0-9._%+-]{1,64}@[a-zA-Z0-9.-]{1,255}\.[a-zA-Z]{2,63})$/';
This pattern adds some additional constraints:
- The local part (before the @ symbol) can be up to 64 characters long
- The domain name (after the @ symbol) can be up to 255 characters long
- The TLD (after the last dot) can be up to 63 characters long
Keep in mind that email address validation is a complex topic, and this pattern is still not foolproof. If you need to validate email addresses for a specific use case, it's recommended to use a dedicated library or service that specializes in email validation.