在原始电子邮件头的“收件人”和“发件人”字段中,似乎有许多可接受的电子邮件地址格式...
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 );
}
这里有什么遗漏吗?有没有更好的方法推荐?