如何将PHP的eregi更改为preg_match [英] How to change PHP's eregi to preg_match

查看:134
本文介绍了如何将PHP的eregi更改为preg_match的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何将ereg表达式转换为PHP中的preg?


我需要帮助,下面是一个很小的非常基本的正则表达式,有点验证一个电子邮件,我确实意识到它不起作用最大,但是我的需要现在是可以的。 >

它目前使用PHP的 eregi函数,php.net说现在是一个折旧功能,我应该使用 preg_match 用preg_match替换erei不行,有人可以告诉我如何使它工作吗?

  function validate_email($ email){
if(!eregi(^ [[:alnum:]] [a-z0-9 _.-] * @ [a-z0-9 .-] + \。[az] {2,4} $ ,$ email)){
echo'bad email';
} else {
echo'good email';
}
}
函数validate_email($ email){
if(!preg_match(^ [[alnum:]] [a-z0-9 _.-] * @ [a-z0-9 .-] + \。[az] {2,4} $,$ email)){
echo'bad email';
} else {
echo'good email';
}
}


解决方案

Perl风格的正则表达式模式总是需要分隔。字符串中的第一个字符被认为是分隔符,所以这样:

  function validate_email($ email){
if(!preg_match(/ ^ [[:alnum:]] [a-z0-9 _.-] * @ [a-z0-9 .-] + \。[az] {2,4} $ / i,$ email)){
echo'bad email';
} else {
echo'good email';
}
}

您的初始尝试不起作用的原因是因为正在尝试使用 ^ 作为分隔符,但(显然)发现正则表达式的末尾没有匹配的 ^


Possible Duplicate:
How can I convert ereg expressions to preg in PHP?

I need help, below is a small VERY basic regex to somewhat validate an email, I do realize it does not work the greatest but for my needs it is ok for now.

It currently uses PHP's eregi function which php.net says is now a depreciated function and I should use preg_match instead, simply replacing erei with preg_match does not work, can someone show me how to make it work?

function validate_email($email) {
    if (!eregi("^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$", $email)) {
        echo 'bad email';
    } else {
        echo 'good email';
    }
}
function validate_email($email) {
    if (!preg_match("^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$", $email)) {
        echo 'bad email';
    } else {
        echo 'good email';
    }
}

解决方案

Perl-style regex patterns always need to be delimited. The very first character in the string is considered the delimiter, so something like this:

function validate_email($email) {
    if (!preg_match("/^[[:alnum:]][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i", $email)) {
        echo 'bad email';
    } else {
        echo 'good email';
    }
}

The reason your initial attempt didn't work is because it was trying to use ^ as the delimiter character but (obviously) found no matching ^ for the end of the regex.

这篇关于如何将PHP的eregi更改为preg_match的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆