Php valid email regex
A classic question!
In PHP, you can use the following regular expression to validate an email address:
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
This regular expression matches most common email address formats, including:
- Local part (before the
@
symbol): one or more characters (letters, digits, dot, hyphen, underscore, percent, plus) - Domain (after the
@
symbol): one or more characters (letters, digits, dot, hyphen) - Top-level domain (after the last dot): two or more characters (letters only)
Here's a breakdown of the regular expression:
^
matches the start of the string[a-zA-Z0-9._%+-]+
matches one or more characters that are letters (both uppercase and lowercase), digits, dot, hyphen, underscore, percent, or plus@
matches the@
symbol[a-zA-Z0-9.-]+
matches one or more characters that are letters (both uppercase and lowercase), digits, dot, or hyphen\.
matches a dot (escaped with a backslash because dot has special meaning in regex)[a-zA-Z]{2,}
matches two or more characters that are letters only (the top-level domain)$
matches the end of the string
You can use this regular expression in PHP like this:
$email = '[email protected]';
if (preg_match('/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/', $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 whether the format of the email address is valid.