使用PHP解析电子邮件地址?

时间:2011-09-29 15:03:59

标签: php regex parsing email

this question类似,我如何解析这种格式的电子邮件地址,

"Bob Smith" <bob@company.com>, joe@company.com, "John Doe"<john@company.com>

得到这样的结果:

array(
    'bob@company.com'=>'Bob Smith'
    'joe@company.com'=>''
    'john@company.com'=>'John Doe'
);

5 个答案:

答案 0 :(得分:10)

好吧,你可以使用mailparse_rfc822_parse_addresses(),这正是如此。它是PECL扩展,因此可能更容易使用评论中提到的Mail_RFC822::parseAddressList()

答案 1 :(得分:6)

这应该适用于任何事情:

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

结果:

Array
(
    [bob@company.com] => Bob Smith
    [joe@company.com] => 
    [john@company.com] => John Doe
    [billy@company.com] => Billy Doe
)

答案 2 :(得分:1)

  1. 以逗号分隔字符串
  2. 如果有效的电子邮件然后存储,如果否
    1. rtrim the'&gt;'字符
    2. 以'&lt;'爆炸
    3. 修剪字符串('“'和'')

答案 3 :(得分:1)

这是一段完整有效的代码,甚至可以验证电子邮件是否正确;)

<?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 />";
}

?>

答案 4 :(得分:1)

对于类似的任务,我使用了以下正则表达式:

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

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

PHP代码:

$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);
}