使用filter_var()和preg_match()进行PHP电子邮件验证

时间:2014-02-12 15:42:16

标签: php forms validation email

我正在尝试使用良好电子邮件验证来构建表单,我正在尝试将filter_var()preg_match()结合使用,但是我的if语句不在下面工作。似乎只有其中一个条件得到满足。我怎么能写这个以便它起作用?

$email = (isset($scrubbed['email']))
    ? filter_var($scrubbed['email'], FILTER_VALIDATE_EMAIL, FILTER_SANITIZE_EMAIL)
    : NULL
;

if ((!$email) && (!preg_match("/^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$/", $email))) {
    echo 'Invalid Email Address, please correct errors';
} else {
    $email = strip_tags($scrubbed['email']);
}

2 个答案:

答案 0 :(得分:2)

再次验证电子邮件地址的目的是什么? PHP filter_var()已经允许各种电子邮件变体,您可能永远不会创建一个甚至接近他们使用的正则表达式。

我使用的电子邮件验证如下所示(适用于您的代码):

<?php

if (isset($scrubbed["email"])) {

    // @see http://stackoverflow.com/a/574698/1251219
    if (strlen($scrubbed["email"]) > 254) {
        echo "The email address is too long: it must be 254 or less.";
    }

    // Validate syntax with PHP.
    if (($email = filter_var($scrubbed["email"], FILTER_VALIDATE_EMAIL)) === false) {
        echo "The email address has an invalid syntax.";
    }

    // Validate DNS reachability.
    $host = substr($email, strrpos($email, "@") + 1) . ".";

    if (!checkdnsrr($host, "A") && !checkdnsrr($host, "AAAA") && !checkdnsrr($host, "MX")) {
        echo "The email address is unreachable.";
    }
}

?>

有没有想过PHP的正则表达式是什么样的?

/^(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){255,})(?!(?:(?:\x22?\x5C[\x00-\x7E]\x22?)|(?:\x22?[^\x5C\x22]\x22?)){65,}@)(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22))(?:\.(?:(?:[\x21\x23-\x27\x2A\x2B\x2D\x2F-\x39\x3D\x3F\x5E-\x7E]+)|(?:\x22(?:[\x01-\x08\x0B\x0C\x0E-\x1F\x21\x23-\x5B\x5D-\x7F]|(?:\x5C[\x00-\x7F]))*\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\]))$/iD

可以在Comparing E-mail Address Validating Regular Expressions找到更多信息。

答案 1 :(得分:0)

if ((!$email) && (!preg_match("/^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$/", $email)))

应该是

if ((!$email) || (!preg_match("/^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$/", $email)))

...