在 To: 和 From: 原始电子邮件标题中似乎有许多可接受的电子邮件地址格式......
person@place.com
person <person@place.com>
person
Another Person <person@place.com>
'Another Person' <person@place.com>
"Another Person" <person@place.com>
在没有找到任何有效的 PHP 函数来拆分姓名和地址后,我编写了以下代码。
您可以在 CODEPAD上演示以查看输出...
// validate email address
function validate_email( $email ){
return (filter_var($email, FILTER_VALIDATE_EMAIL)) ? true : false;
}
// split email into name / address
function email_split( $str ){
$name = $email = '';
if (substr($str,0,1)=='<') {
// first character = <
$email = str_replace( array('<','>'), '', $str );
} else if (strpos($str,' <') !== false) {
// possibly = name <email>
list($name,$email) = explode(' <',$str);
$email = str_replace('>','',$email);
if (!validate_email($email)) $email = '';
$name = str_replace(array('"',"'"),'',$name);
} else if (validate_email($str)) {
// just the email
$email = $str;
} else {
// unknown
$name = $str;
}
return array( 'name'=>trim($name), 'email'=>trim($email) );
}
// test it
$tests = array(
'person@place.com',
'monarch <themonarch@tgoci.com>',
'blahblah',
"'doc venture' <doc@venture.com>"
);
foreach ($tests as $test){
echo print_r( email_split($test), true );
}
我在这里错过了什么吗?谁能推荐一个更好的方法?