2011-09-29 145 views
1

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

回答

1
  1. 用逗號
  2. 爆炸串
  3. 如果有效的電子郵件然後將其存儲,如果沒有
    1. rtrim'>'字符
    2. 爆炸由 '<'
    3. 修剪字符串(「 '' 和'')
+0

我想說這不會工作。但我認爲它會正常工作!開始編碼。 –

+0

如果您想獲取名稱和電子郵件地址,這種方法效果不錯。名字可以是「Ballinger,John <[email protected]>,電子郵件2」,但對於純粹的電子郵件來說,它並不壞。 (我想要名稱和電子郵件,並且不能安裝PHP擴展。) –

1

這是下面的代碼完全工作的一塊甚至驗證電子郵件是否正確與否;)

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

?> 
5

這應該與幾乎任何工作:

$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'<[email protected]>' – dlo

0

$ emails = explode(「,」,$ your_email_清單);

用逗號

爆炸串

這不是有效的解決方案,因爲逗號可能是名稱的一部分:「姓氏,名字」