tags:

views:

59

answers:

5

Hi,

I need to extract the email address out of this mailbox string. I thought of str_replace but the display name and the email address is not static so I don’t know how to do this using regular expressions.

Example: "My name <[email protected]>" should result in "[email protected]".

Any ideas?

Thanks Matthy

+7  A: 

You can use imap_rfc822_parse_adrlist to parse that address:

$addresses = imap_rfc822_parse_adrlist('My name <[email protected]>');
Gumbo
+1 PHP has everything.
BoltClock
PHP saves the day with an amazing list of obscure functions. :)
Josh K
Yeah, I remember the `easter_date()` answer (which is gone now) to that code golf question.
BoltClock
+1  A: 

If you know that the string is surrounded by < and > you can simply split out according to that.

This assumes that you will always have only one pair of < and > surrounding the string, and it will not ensure that the result is an email pattern.

Otherwise you can always read up on email regex patterns.

Josh K
A: 

or Look up regular expressions (preg_match).

something like: [^<]<([^>])>;

Daniel Hai
+1  A: 

at face value, the following will work:

preg_match('~<([^>]+)>~',$string,$match);

but i have a sneaking suspicion you need something better than that. There are a ton of "official" email regex patterns out there, and you should be a bit more specific about the context and rules of the match.

Crayon Violent
people who downvote w/out giving a reason ftw. Oh right. "make my answer better by downvoting everybody else" tactic ftw. yay!
Crayon Violent
this was the only one that actualy worked.... thanks man
matthy
In my app I personally use * after angle the brackets to ensure that all email address formats match even when users don't specify a title and email address
Steve Smith
A: 
$s = 'My name <[email protected]>';
$s = substr(($s = substr($s, (strpos($s, '<')+1))), 0, strrpos($s, '>'));

If you are sure its already in the given format, the following is more efficient

$s = substr($s, (strpos($s, '<')+1), -1);

Both results in: '[email protected]'

JackFuchs
This seems dangerous for me, since the name can probably contain "<" and ">" characters. `strrpos` instead of `strpos` will avoid this problem.
MainMa
Sure, this was just a tip on how to do it efficiently. I do not understand why people are voting up on imap_rfc822_parse_adrlist(). The use of imap_rfc822_parse_adrlist() is the absolute overkill for this easy task.
JackFuchs