在PHP中使用preg_match验证电子邮件地址时遇到问题


Having a problem validating email address in PHP with preg_match

代码:

if(trim($_POST['email']) == '')  {
        $hasError = true;
    } else if (!preg_match("/^[A-Z0-9._%-]+@[A-Z0-9._%-]+'.[A-Z]{2,4}$", trim($_POST['email']))) {
        $hasError = true;
    } else {
        $email = trim($_POST['email']);
    }

错误信息:

警告:preg_match() [function。:在/home/bigsilkd/public_html/UBA/join.php第22行

中没有找到结束分隔符'/'

就是这么写的:

preg_match("/^[A-Z0-9._%-]+@[A-Z0-9._%-]+'.[A-Z]{2,4}$"
应该

preg_match("/^[A-Z0-9._%-]+@[A-Z0-9._%-]+'.[A-Z]{2,4}$/"
                                                      ^
                                                      |
                                  This was missing ---/

您不应该使用正则表达式来验证电子邮件。例如,你的正则表达式不允许我的电子邮件地址+@example.org,这是一个正常和有效的电子邮件。保存我的邮件!由于糟糕的表单验证,它正在消亡!

使用filter_var !
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    // email is valid
}