Php validate email regex
A classic!
In PHP, you can use a regular expression to validate an email address. Here's a commonly used pattern:
$regex = '/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/';
Let's break it down:
^
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)$
matches the end of the string
You can use this regular expression in PHP like this:
$email = '[email protected]';
if (preg_match($regex, $email)) {
echo 'Valid email address!';
} else {
echo 'Invalid email address!';
}
Note that this regular expression does not validate whether the email address actually exists or is in use. It only checks the format of the email address.
Also, keep in mind that this regular expression is not foolproof and may not catch all invalid email addresses. For example, it does not check for the presence of a local part (the part before the @ symbol) or the domain name.
If you need a more robust email validation, you may want to consider using a dedicated library or service, such as PHPMailer or EmailValidator.