Parse e-mail addresses with PHP?

2020-02-06 09:58发布

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'
);

5条回答
对你真心纯属浪费
2楼-- · 2020-02-06 10:15

For a similar task I've used the following regex:

\s*(?:"([^"]*)"|([^,""<>]*))?\s*(?:(?:,|<|\s+|^)([^<@\s,]+@[^>@\s,]+)>?)\s*

https://regex101.com/r/Lpsjmr/1

PHP code:

$str = '"Bob Smith" <bob@company.com>, joe@company.com, "John Doe"<john@company.com>, Billy Doe<billy@company.com>';
if (preg_match_all('/\s*(?:"([^"]*)"|([^,""<>]*))?\s*(?:(?:,|<|\s+|^)([^<@\s,]+@[^>@\s,]+)>?)\s*/', $str, $matches, PREG_SET_ORDER) > 0) {
    $matches = array_map(function($x) { return [$x[1] . $x[2], $x[3]]; }, $matches);
    print_r($matches);
}
查看更多
做自己的国王
3楼-- · 2020-02-06 10:15

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.

查看更多
Summer. ? 凉城
4楼-- · 2020-02-06 10:20

This is a fully working piece of code below that even validates whether the email is correct or not ;)

<?php
$mails = '"Bob Smith" <bob@company.com>, joe@company.com, "John Doe"<john@company.com>';

$records = explode(",",$mails);

foreach($records as $r){
  preg_match("#\"([\w\s]+)\"#",$r,$matches_1);
  $name = $matches_1[1];


  preg_match("/[^0-9<][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}/i",$r,$matches_2);
  $email = $matches_2[0];

  echo "Name: $name <br /> Email: $email <br />";
}

?>
查看更多
叛逆
5楼-- · 2020-02-06 10:33

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
)
查看更多
爷的心禁止访问
6楼-- · 2020-02-06 10:36
  1. Explode the string by comma
  2. If valid email then store it, if NO
    1. rtrim the '>' character
    2. explode by '<'
    3. trim the string for ('"', and ' ')
查看更多
登录 后发表回答