Page 1 of 1

Validate email address in PHP

Posted: 11 Jan 2015, 09:34
by MarPlo
What is the best way to validate an email address in PHP?
I currently use preg_match() with a RegExp:

Code: Select all

$email = 'some_name@domain.com';
if(preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/', $email)) {
  echo 'valid email';
}
else {
  echo 'not valid email';
} 
Is there a better /simpler method?

Validate email address in PHP

Posted: 11 Jan 2015, 09:42
by Admin
The easiest and safest way to check whether an email address is well-formed is to use the filter_var() function:

Code: Select all

$email = 'some_name@domain.com';
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
  echo 'valid email';
}
else {
  echo 'not valid email';
}