PHP email validation using regex

02Jan

PHP email validation using regex

by Craig Mayhew on Sun 2nd Jan 2011 under Code
I keep seeing PHP where the programmer has written a regular expression to validate an email address.

Don't do that! Use the filter_var() function that php comes with out of the box.



<?php
$emailAddress = 'person@example.com';

if (filter_var($emailAddress , FILTER_VALIDATE_EMAIL)) {
echo $emailAddress,' is considered valid.';
}else{
echo $emailAddress,' is considered invalid.';
}
?>


And if you want to tidy the email address up:


<?php
$sanitizedEmailAddress = filter_var($emailAddress, FILTER_SANITIZE_EMAIL);
?>


PHP   Validation  




© 2005-2021 Craig Mayhew