Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse e-mail addresses with PHP?

Similar to this question, how could I parse e-mail addresses which are in this format,

"Bob Smith" <[email protected]>, [email protected], "John Doe"<[email protected]>

And get the a result like this:

array(
    '[email protected]'=>'Bob Smith'
    '[email protected]'=>''
    '[email protected]'=>'John Doe'
);
like image 435
cwd Avatar asked Nov 30 '22 07:11

cwd


2 Answers

Well, you could use mailparse_rfc822_parse_addresses(), which does exactly that. It's a PECL extension, so it might be easier to use Mail_RFC822::parseAddressList() as mentioned in the comments.

like image 156
mario Avatar answered Dec 02 '22 22:12

mario


This should work with just about anything:

$str = '"Bob Smith" <[email protected]>, [email protected], "John Doe"<[email protected]>, Billy Doe<[email protected]>';
$emails = array();

if(preg_match_all('/\s*"?([^><,"]+)"?\s*((?:<[^><,]+>)?)\s*/', $str, $matches, PREG_SET_ORDER) > 0)
{
    foreach($matches as $m)
    {
        if(! empty($m[2]))
        {
            $emails[trim($m[2], '<>')] = $m[1];
        }
        else
        {
            $emails[$m[1]] = '';
        }
    }
}

print_r($emails);

Result:

Array
(
    [[email protected]] => Bob Smith
    [[email protected]] => 
    [[email protected]] => John Doe
    [[email protected]] => Billy Doe
)
like image 36
Luke Avatar answered Dec 02 '22 22:12

Luke