Home » Php » php – Get email address from mailbox string

php – Get email address from mailbox string

Posted by: admin July 12, 2020 Leave a comment

Questions:

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

How to&Answers:

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.

Answer:

You can use imap_rfc822_parse_adrlist to parse that address:

$addresses = imap_rfc822_parse_adrlist('My name <[email protected]>');

Answer:

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.

Answer:

or Look up regular expressions (preg_match).

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

Answer:

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

$s = 'My name <[email protected]>';
$s = substr(($s = substr($s, (strpos($s, '<')+1))), 0, strrpos($s, '>'));

Results in

[email protected]