If you’re a web programmer, there will come a time when you need to validate an email address. It’s going to happen, so just accept it. In newer versions of PHP, there is built in functionality for this. However, for those of us not lucky enough to be running the latest and greatest version, we can use regular expressions.
The following PHP function will validate email addresses using regular expressions. True is returned on success, and false is returned otherwise.
1 2 3 | function validate_email($email) { return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email); } |
2 replies on “Validate Email Addresses With PHP”
Everytime I see a “validate email with RegEx” article on a blog, I cringe. 99.9% of them are wrong, some of them are dangerously wrong if someone were to implement them.
Here are four VALID emails, off the top of my head your validator expression fails:
my+test@gmail.com
“test.test”@gmail.com
bob@163.34.66.122
valid@about.museum
http://www.dominicsayers.com/isemail/results.php has an excellent post on validating email according to the RFC
Thank you for the link at the end of your comment. That is by far the best post I’ve ever read on validating email address. I’ll be sure to update this post in the near future with better information.