Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP search a string for a email address

Tags:

regex

php

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 [email protected]. I am also on Twitter."

I am a bit stumped, I know I can search if it exists at all with \b around it but how do I return what is found.

Thanks.

like image 921
joobaal Avatar asked Jan 12 '10 17:01

joobaal


1 Answers

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 [email protected]. 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]; // [email protected]
like image 194
Sampson Avatar answered Sep 17 '22 22:09

Sampson