PHP: Email regex.

You should not be validating emails with regular expressions.

To make a long story short, 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”, we noticed that about 60-70% of the listed results were terrible. Many of these PHP snippet websites and help forums contained bad regex examples that will actually reject valid email addresses.

If you want to validate an email address in PHP, then you can use 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 on the Internet.

Take a look at the following example.

if(filter_var($emailAddress, FILTER_VALIDATE_EMAIL)) {
     //The email address is valid.
} else{
     //The email address is invalid.

Compare the code above to this example that we 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.

if (!preg_match("/[-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+.[a-zA-Z]{2,4}/", $emailAddress)){
    //Email address is invalid.

You can tell that the regex code above is inadequate just by looking at short it is. If you look at any of the regex examples that attempt to stay true to RFC 822, then you’ll see that they are about 1,000 times longer.

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 developers are of the opinion that you should validate via a link that is sent out to the user’s email.

For example.

  1. A user signs up to your website.
  2. Create a token for that user and then send it out to the user’s email address.
  3. If they click on the link containing the token, mark their email address as being valid.
  4. Until the link is clicked on, presume that the email is invalid.

Of course, not everyone likes the thought of this. This is because many hosting solutions can limit how many emails your app can send per hour.

This is especially true for shared hosting solutions; many of which will limit the number of emails you can send out in an effort to save resources and cut down on spam.

There are also developers who simply do not care about people who have “quirky” email addresses, regardless of whether they are valid or not. For example, how many times are you likely to come across email addresses such as “Test Email Please Ignore!”

Chances are, this is the first time you’ve seen an email address with spaces, an exclamation mark and double quotes in it.

Our opinion? Just stick to using the filter_var function unless it is rejecting a valid email format that you specifically want to allow.