Thursday, September 26, 2013

Perfect PHP Email Regex

This is a perfect regular expression for validating email address from text inputs form. It matches common email address format. Here is the email regex I often use on PHP or Javascipt.

/([a-z0-9_]+|[a-z0-9_]+\.[a-z0-9_]+)@(([a-z0-9]|[a-z0-9]+\.[a-z0-9]+)+\.([a-z]{2,4}))/i

The regular expression above matches email addresses like:
  • myemail@example.com
  • my_email@example.com
  • my.email@example.com
But not for:
  • myemail.@example.com
  • .myemail@example.com
You can find emails from long string using this regular expression. Below is the example usage:

<?php
$regex = '/([a-z0-9_]+|[a-z0-9_]+\.[a-z0-9_]+)@(([a-z0-9]|[a-z0-9]+\.[a-z0-9]+)+\.([a-z]{2,4}))/i';
$string = "This is string contains email@example.com and also this one: test@example.com";
if(preg_match_all($regex,$string,$match)) {
    echo "<pre>";
    print_r($match[0]);
    echo "</pre>";
}
?>

it will returns:

Array ( 
    [0] => email@example.com 
    [1] => test@example.com
)

But if you just want to validate from HTML input forms, you may use PHP filter_var instead.
<?php
if(filter_var('email@example.com', FILTER_VALIDATE_EMAIL)) {
     echo "email is valid";
}
?>



No comments :

Post a Comment