getting emails out of string - regex syntax + preg

2019-03-15 22:33发布

问题:

i'm trying to get emails out of a string.

$string = "bla bla pickachu@domain.com MIME-Version: balbasur@domain.com 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 im getting is : Delimiter must not be alphanumeric or backslash

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

what should i do? thanks in advance!

回答1:

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';


回答2:

You just need to wrap your pattern in a proper delimiter, like forward slashes. Like so:

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


回答3:

When using PCRE regex functions it require to enclose the pattern by delimiters:

PHP Delimiters

Often used delimiters are forward slashes (/), hash signs (#) and tildes (~). The following are all examples of valid delimited patterns.

/foo bar/
#^[^0-9]$#
+php+
%[a-zA-Z0-9_-]%

Then you must correct this line to:

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

or

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