这是我使用的一个函数。它不仅仅是通过正则表达式运行电子邮件地址,但到目前为止,它是我发现的最完整的解决方案:
function validEmail($email, $skipDNS = false)
{
$isValid = true;
$atIndex = strrpos($email, "@");
if (is_bool($atIndex) && !$atIndex)
{
$isValid = false;
}
else
{
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64)
{
// local part length exceeded
$isValid = false;
}
else if ($domainLen < 1 || $domainLen > 255)
{
// domain part length exceeded
$isValid = false;
}
else if ($local[0] == '.' || $local[$localLen-1] == '.')
{
// local part starts or ends with '.'
$isValid = false;
}
else if (preg_match('/\\.\\./', $local))
{
// local part has two consecutive dots
$isValid = false;
}
else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
{
// character not valid in domain part
$isValid = false;
}
else if (preg_match('/\\.\\./', $domain))
{
// domain part has two consecutive dots
$isValid = false;
}
else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local)))
{
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local)))
{
$isValid = false;
}
}
if(!$skipDNS)
{
if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
{
// domain not found in DNS
$isValid = false;
}
}
}
return $isValid;
}
该函数有一个可选的 $skipDNS 参数,如果您不想验证主机的 MX 记录,可以将其设置为 TRUE。否则,该函数将尝试验证提供的电子邮件地址是否实际映射到真实的电子邮件服务器。
需要注意的是,大多数 RegEx 电子邮件验证技术将验证大多数电子邮件地址,但它们很可能会允许一些精心设计的无效地址,或者最糟糕的情况。在一些更晦涩但有效的电子邮件地址上失败。有关更多信息,您可能需要查看Internet Message Formats RFC,它描述了电子邮件地址的允许格式。