tags:

views:

92

answers:

3

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.

A: 

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]
Jonathan Sampson
Be aware that in this case, you will need to remove the ^ and $ from the beginning and end of your pattern - ^ means to match the start of the string, and $ matches the end of the string, so it won't find a "match" unless the email is the whole string. To search for a contained email address, you would change:"^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$" to "[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})"
Renesis
I decided to carry on using eregi, thanks for the pointer Renesis.
joobaal
Oh and thanks for helping too Jonathan!
joobaal
Joobool, remember to accept the answer that you found helpful.
Jonathan Sampson
+1  A: 

add $regs as the last argument:

eregi("...", $email, $regs);
Antony Hatchkins
Works great, thanks!
joobaal
Joobool, if you found this answer helpful, accept it.
Jonathan Sampson
A: 

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.

symcbean