ThisĀ horrendousĀ regular expression will parse a string and return a valid email address from it.

$email = "<'Freddy'> fred@live.com";
preg_match('/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/', $email, $match);
echo $match[0];

This will return:

fred@live.com

Basically, if you pass an array as the third parameter of the preg_match method, it will be filled with the preg_match results, and the first item of the array will be the matching string. If you use capturing groups, these will also be filled. Read more about preg_match at the PHP site here.

I am told that this expression will match 99.9% of valid email addresses in the wild.

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.