验证电子邮件ID中的Preg Match问题

时间:2016-01-22 07:43:56

标签: php regex preg-match-all

为什么下面的代码会将电子邮件ID返回为false或无效?

<?php
    $okay = preg_match(
        '/^[A-z0-9_\-]+[@][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z.]{2,4}$/', 
        "caree.india.support@gmail.com"
    );
    echo $okay;
?>

1 个答案:

答案 0 :(得分:2)

PHP本身已经有一个功能来验证电子邮件,我建议使用它来代替正则表达式。

<?php
    $email_a = 'caree.india.support@gmail.com';
    $email_b = 'Random words';

    if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
        echo "This ($email_a) email address is considered valid.";
    }
    if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
        echo "This ($email_b) email address is considered valid.";
    }
?>

更多相关信息可以在这里找到:
http://php.net/manual/en/function.filter-var.php
http://php.net/manual/en/filter.examples.validation.php