solvit.io

Validate an email address in PHP using a regular expression

Solution #1

You can't validate an email address with a regular expression. The only valid solution is to send a confirmation email to your users.

Solution #2

This regular expression validates most of the real-world email addresses, but it fails with some of the edge cases allowed by the email specification:

function isValidEmail($emailAddress)
{
    return 1 === preg_match("/(?:[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/", $emailAddress);
}

$isEmail = isValidEmail($emailAddress);
Example
$result = isValidEmail('[email protected]');
// $result = true
$result = isValidEmail('[email protected]');
// $result = true
$result = isValidEmail('user @example.org');
// $result = false
$result = isValidEmail('[email protected]');
// $result = false

See the RFC 3696 for more details about the syntax of email addresses.

Find more solutions about: , , , ,