Search code examples
phpregexpreg-matchpreg-match-all

getting emails out of string - regex syntax + preg_match_all


I'm trying to get emails out of a string:

$string = "bla bla [email protected] MIME-Version: [email protected] bla bla bla";
$matches = array();
$pattern = '\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b';
preg_match_all($pattern,$string,$matches);
print_r($matches);

The error I'm getting is :

Delimiter must not be alphanumeric or backslash

I got the regex syntax from here http://www.regular-expressions.info/email.html


Solution

  • Like this

    $pattern = '/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i';
    

    Or smaller version :)

    $pattern = '/[a-z\d._%+-]+@[a-z\d.-]+\.[a-z]{2,4}\b/i';