Validating an e-mail address according to RFC 2822

E-mail addresses are bitches!
There, now that is said I can tell why.

Should you ever have time on your hands you should read RFC 2822, it provides an interesting (though somewhat dull) background into e-mail messaging. Alas one can also see why it is so hard to validate an e-mail address, it is an extremely flexible format which is quite hard to check.

Fortunately I found a little gem on http://www.regular-expressions.info/email.html which is all about parsing E-mail addresses with regular expressions. For your (and my own) leasure I have prepared a snippet which you can copy paste right into your code.
One small note: this regexp is not fast! It is designed for accuracy, thus I’d advise so I would recommend to on a high traffic site to use the adaptations proposed on the website above.

$regexp = "/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[x01-x08x0bx0cx0e-x1fx21x23-x5bx5d-x7f]|\[x01-x09x0bx0cx0e-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-x08x0bx0cx0e-x1fx21-x5ax53-x7f]|\[x01-x09x0bx0cx0e-x7f])+)])$/";
var_dump(preg_match($regexp, '[email protected]'));

Have fun!

Leave a Reply

Your email address will not be published. Required fields are marked *