3

I have this regex:

^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$

Which is suppose to parse full email with name and everything, I couldn't get it to run in PHP, please help?

Here is what I have tried:

$test = "Joe Doe <doe@example.com>";
$emailRegex = '@^((?>[a-zA-Z\d!#$%&\'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&\'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$@';
preg_match($emailRegex, $test, $curResult);
print_r($curResult);
Bill Software Engineer
  • 7,362
  • 23
  • 91
  • 174

4 Answers4

3

In PHP you don't need a monster regex like that, you can just use the built-in validator: http://www.php.net/manual/en/filter.examples.validation.php

For example, only the first echo will be executed:

<?php
$email_a = 'joe@example.com';
$email_b = 'bogus';

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "This ($email_a) email address is considered valid.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "This ($email_b) email address is considered valid.";
}
?>
SomeKittens
  • 38,868
  • 19
  • 114
  • 143
  • 2
    Beware FILTER_VALIDATE_EMAIL - http://stackoverflow.com/questions/13494114/how-consistent-is-filter-validate-email. – brandonscript Jan 16 '14 at 20:02
  • 1
    I am not trying to filter email though, I am trying to parse them. – Bill Software Engineer Jan 16 '14 at 20:04
  • 1
    `var_dump(filter_var("Joe Doe ", FILTER_VALIDATE_EMAIL));` => false. The OP isn't trying to parse an e-mailaddress, the OP is trying to parse an address string, which is not quite the same thing. – Wrikken Jan 16 '14 at 20:28
1

Keep it simple. Since we know we can use this to validate almost any email address in an uncomplicated way:

(^[^ ]+@[^ ]+\.[^ ].+$)

One step further will let us grab the name too:

^(.*?) *(<[^ ]+@[^ ]+\.[^ ].+>)$

http://regex101.com/r/wT6uX8

brandonscript
  • 68,675
  • 32
  • 163
  • 220
1

I would not write a custom function if PHP's imap_rfc822_parse_adrlist does exactly what you need.

Wrikken
  • 69,272
  • 8
  • 97
  • 136
0

Try,

$emailRegex = "/([\w\s]+)\<(\w+([-+.']\w+)@\w+([-.]\w+).\w+([-.]\w+)*)/i";

I hope this will help you

vpx
  • 108
  • 6