getting emails out of string - regex syntax + preg_match_all [closed]

狂风中的少年 提交于 2019-12-03 12:39:04

问题


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


来源:https://stackoverflow.com/questions/15050915/getting-emails-out-of-string-regex-syntax-preg-match-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!