I have a database that contains a collection of text email addresses that need to be parsed. They can be in one of two formats in the "ToAddress:" field
1) jeff <[email protected]>; john <[email protected]>; [email protected]; [email protected]; jamie <[email protected]>
or
2) [email protected]
I need the addresses parsed into a PHP array with both parts name and email even if there is no name.
I have been partially successful with the following, but it seems to be broken when there is no name or when there are no "<" surrounding the email. Would love some advice on how to fix it.
$emails = array();
$e = array();
if(preg_match_all('/\s*"?([^><,"]+)"?\s*((?:<[^><,]+>)?)\s*/', $vToAddr, $matches, PREG_SET_ORDER) > 0)
{
foreach($matches as $m)
{
if(! empty($m[2]))
{
$emails= array("email" => trim($m[2], '<>'), "name" => trim($m[1],';'));
}
else
{
$emails= array("email" => trim($m[2], '<>'), "name" => "");
}
array_push($e,$emails);
}
}
I looked into How to parse formatted email address into display name and email address? where I got the original RegEx from, but it fails with the example above.