开发者

PHP search a string for a email address

开发者 https://www.devze.com 2022-12-16 07:48 出处:网络
Hi Im attempting to search a string to see whether it contains a email address - and then return it. A typical email vaildator expression is:

Hi Im attempting to search a string to see whether it contains a email address - and then return it.

A typical email vaildator expression is:

eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);

However how would I search if that is in a string, for example return the email address in the string:

"Hi my name is Joe, I can be contacted at joe@mysite.com. I am also on Twitter."

I am a bit stumped, I know I can search if it exists at all with \b arou开发者_如何学运维nd it but how do I return what is found.

Thanks.


You could use preg_match(), which would output it to an array for use.

$content = "Hi my name is Joe, I can be contacted at joe@mysite.com. I am also on Twitter.";
preg_match("/[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})/i", $content, $matches);

print $matches[0]; // joe@mysite.com


add $regs as the last argument:

eregi("...", $email, $regs);


A better PCRE for extracting an ADDR_SPEC is:

 /[a-z0-9\._%+!$&*=^|~#%'`?{}/\-]+@([a-z0-9\-]+\.){1,}([a-z]{2,6})/

But if you really want to extract an RFC 2822 then you need something like:

 /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/

C.

0

精彩评论

暂无评论...
验证码 换一张
取 消