PHP: Email regex.

You should not be validating emails with regular expressions. Simply put: The vast majority of regex snippets on the Internet are incorrect. Most of them are far too simple and ill-equipped to adequately deal with something as complex as an email address. While searching Google for terms such as “PHP validate email regex example”, I noticed that about 60-70% of the listed results were utter mush. Most of these PHP snippet websites contained crappy regex examples that will actually reject valid email addresses.

If you want to validate email addresses in PHP, then you can make use of the filter_var function. The filter_var function uses a regex itself. However, the regex that filter_var uses is far more complex (and informed) than the vast majority of examples that you will find floating around the Internet. Example code:

Compare the code above to this example that I found on another article and you’ll find that FILTER_VALIDATE_EMAIL is a lot more accurate when it comes to the email specifications set down in RFC 822:

I can tell that the code above is inadequate just by looking at it. If you look at any of the regex examples that attempt to stay true to RFC 822, you’ll see that they are about 1000 times longer than the regex that is used in the above code.

Don’t validate email addresses.

Another popular approach is to not validate email addresses at all. Because even the regex behind filter_var has its limitations, a lot of people are of the opinion that you should validate via a link that is sent out to the user’s email. Example:

  1. User signs up.
  2. Create a token for that user and then send it out to the email address that they provided.
  3. If they click on the link containing the token, mark their email address as being validated.
  4. Until the link is clicked on, assume that the email is invalid.

Of course, not everyone likes the thought of this, simply because many hosting solutions are pretty skimpy when it comes to how many emails you can send per hour / day. This is especially true for shared hosting solutions; many of which will limit the number of emails that you can send out in an effort to save resources and cut down on spam. There are also people who simply do not care about people that have “quirky” email addresses, regardless of whether they are valid or not. For example, how many times have you come across email addresses such as: “Test Email Please Ignore!”

Chances are, this is the first time that you have come across such an oddly-formatted email address.

My opinion? Stick to filter_var unless it is rejecting a valid email format that you specifically want to allow.

Facebook Comments