简体   繁体   中英

Get email address from mailbox string

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@example.com> " should result in " email@example.com ".

Any ideas?

Thanks Matthy

您可以使用imap_rfc822_parse_adrlist来解析该地址:

$addresses = imap_rfc822_parse_adrlist('My name <email@gmail.com>');

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.

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 .

or Look up regular expressions (preg_match).

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

I'm coming from a time and from projects where Regex was to expensive for easy string extraction.

$s = 'My name <email@gmail.com>';
$s = substr(($s = substr($s, (strpos($s, '<')+1))), 0, strrpos($s, '>'));

Results in

email@gmail.com

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM