Skip to content

Instantly share code, notes, and snippets.

@upsuper
Created April 17, 2012 06:43
Show Gist options
  • Save upsuper/2403951 to your computer and use it in GitHub Desktop.
Save upsuper/2403951 to your computer and use it in GitHub Desktop.
检验是否为有效的电子邮件地址的 PHP 函数
<?php
/**
* 检验是否为有效的电子邮件地址
*
* 根据 http://www.linuxjournal.com/article/9585 编写
*
* @param string $email
* @return bool
*/
function is_valid_email($email) {
// 是否存在@
$at_index = strrpos($email, '@');
if ($at_index === false)
return false;
// 分离信息
$local = substr($email, 0, $at_index);
$domain = substr($email, $at_index + 1);
$local_len = strlen($local);
$domain_len = strlen($domain);
// 检查有效性
if ($local_len < 1 || $local_len > 64)
return false;
if ($domain_len < 1 || $domain_len > 255)
return false;
if ($local[0] == '.' || $local[$local_len - 1] == '.')
return false;
if (strpos($local, '..') !== false)
return false;
if (strpos($domain, '..') !== false)
return false;
if (! preg_match('/^[A-Za-z0-9.-]+[A-Za-z0-9]$/', $domain))
return false;
if (! preg_match('/^"[^"]+"$/', $local)) {
if (! preg_match('/^[A-Za-z0-9!#$%&\'*+\\/=?^_`{|}~.-]+$/', substr($local, 1, -1)))
return false;
}
if (! (checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A')))
return false;
return true;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment