用PHP解析电子邮件地址?

问题描述:

this question相似的,我怎么能解析这些都是这种格式的电子邮件地址,用PHP解析电子邮件地址?

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

,并得到这样的结果:

array(
    '[email protected]'=>'Bob Smith' 
    '[email protected]'=>'' 
    '[email protected]'=>'John Doe' 
); 
+0

[解析RFC 822个以合规的地址可能重复TO头](http://stackoverflow.com/questions/6609195/parse-rfc-822-compliant-addresses-in-a-to-header) – mario

嗯,你可以使用mailparse_rfc822_parse_addresses(),这正是这么做的。这是一个PECL扩展,因此可能会更容易使用Mail_RFC822::parseAddressList(),如评论中所述。

  1. 用逗号
  2. 爆炸串
  3. 如果有效的电子邮件然后将其存储,如果没有
    1. rtrim'>'字符
    2. 爆炸由 '<'
    3. 修剪字符串(“ '' 和'')
+0

我想说这不会工作。但我认为它会正常工作!开始编码。 –

+0

如果您想获取名称和电子邮件地址,这种方法效果不错。名字可以是“Ballinger,John ,电子邮件2”,但对于纯粹的电子邮件来说,它并不坏。 (我想要名称和电子邮件,并且不能安装PHP扩展。) –

这是下面的代码完全工作的一块甚至验证电子邮件是否正确与否;)

<?php 
$mails = '"Bob Smith" <[email protected]>, [email protected], "John Doe"<[email protected]>'; 

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

?> 

这应该与几乎任何工作:

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

结果:

Array 
(
    [[email protected]] => Bob Smith 
    [[email protected]] => 
    [[email protected]] => John Doe 
    [[email protected]] => Billy Doe 
) 
+1

我喜欢简单性,但它不处理名称部分中的逗号,如''Smith,Bob'' – dlo

$ emails = explode(“,”,$ your_email_清单);

用逗号

爆炸串

这不是有效的解决方案,因为逗号可能是名称的一部分:“姓氏,名字”