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" <bob@company.com>, joe@company.com, "John Doe"<john@company.com>

And get the a result like this:

array(
    'bob@company.com'=>'Bob Smith'
    'joe@company.com'=>''
    'john@company.com'=>'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" <bob@company.com>, joe@company.com, "John Doe"<john@company.com>, Billy Doe<billy@company.com>';
$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
(
    [bob@company.com] => Bob Smith
    [joe@company.com] => 
    [john@company.com] => John Doe
    [billy@company.com] => Billy Doe
)
like image 36
Luke Avatar answered Dec 02 '22 22:12

Luke