This is my newer monster script for verifying whether an e-mail "validates" or not. You can feed it strange things and break it, but in production this handles 99.99999999% of the problems I've encountered. A lot more false positives really from typos.
<?php
$pattern = '!^[^@\s]+@[^.@\s]+\.[^@\s]+$!';
$examples = array(
'email@email.com',
'my.email@email.com',
'e.mail.more@email.co.uk',
'bad.email@..email.com',
'bad.email@google',
'@google.com',
'my@email@my.com',
'my email@my.com',
);
foreach($examples as $test_mail){
if(preg_match($pattern,$test_mail)){
echo ("$test_mail - passes\n");
} else {
echo ("$test_mail - fails\n");
}
}
?>
Output
- email@email.com - passes
- my.email@email.com - passes
- e.mail.more@email.co.uk - passes
- bad.email@..email.com - fails
- bad.email@google - fails
- @google.com - fails
- my@email@my.com - fails
- my email@my.com - fails
Unless there's a reason for the look-behind, you can match all of the emails in the string with preg_match_all(). Since you're working with a string, you would slightly modify the regex slightly:
$string_only_pattern = '!\s([^@\s]+@[^.@\s]+\.[^@\s]+)\s!s';
$mystring = '
email@email.com - passes
my.email@email.com - passes
e.mail.more@email.co.uk - passes
bad.email@..email.com - fails
bad.email@google - fails
@google.com - fails
my@email@my.com - fails
my email@my.com - fails
';
preg_match_all($string_only_pattern,$mystring,$matches);
print_r ($matches[1]);
Output from string only
Array
(
[0] => email@email.com
[1] => my.email@email.com
[2] => e.mail.more@email.co.uk
[3] => email@my.com
)