使用PHP中的preg_match()使用RegEx验证电子邮件时出现问题

时间:2011-01-04 16:37:21

标签: php regex

我无法在PHP中使用preg_match()来验证电子邮件地址。我已经使用http://www.regexer.com工具测试了我在Internet上找到的RegEx表达式,并且可以正常使用我在PHP应用程序上使用的相同输入。

RegEx表达式:

^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$

Regexer:http://regexr.com?2sr2a

我在PHP中这样应用它:

$email   = "local@test.com";
$pattern = "/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix";

if (false == preg_match($pattern, $email))
    echo "false";

当然,我通过这封电子邮件和我测试过的其他人得到了错误。我认为这个表达形式很好,因为在regexer上我可以测试并且它有效。我的申请不正确?

提前谢谢!

2 个答案:

答案 0 :(得分:1)

反斜杠字符需要通过将它们加倍来正确转义:

$pattern = "/^([a-z0-9\\+_\\-]+)(\\.[a-z0-9\\+_\\-]+)*@([a-z0-9\\-]+\\.)+[a-z]{2,6}$/ix";

使用此模式,preg_match正确返回1.

答案 1 :(得分:0)

我不确定你的代码有什么问题,但是你有一个功能齐全的php函数来检查电子邮件地址:

function is_validemail($email) 
{
     return preg_match('/^[\w.-]+@([\w.-]+\.)+[a-z]{2,6}$/is', $email);
}

$email = "local@root.ws";

if(is_validemail($email)) { echo ("email validated"); } else { echo ("invalid email given"); }

希望它有所帮助!

相关问题