从 ereg 更改为 preg_match 时 PHP 表达式失败

发布于 2024-09-08 22:21:00 字数 561 浏览 3 评论 0原文

我有一个使用 PHP 的 ereg() 的类,该类已被弃用。 看看 PHP.net,我以为我可以离开并更改为 preg_match()

但我遇到了正则表达式错误,或者它们失败了!

下面是两个例子:

function input_login() {
    if (ereg("[^-_@\.A-Za-z0-9]", $input_value)) { // WORKS
    // if (preg_match("[^-_@\.A-Za-z0-9]", $input_value)) { // FAILS
        echo "is NOT alphanumeric with characters - _ @ . allowed";
    }
}

// validate email
function validate_email($email) {
    // return eregi("^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$", $email); // FAILS
}

I have a class that uses PHP's ereg() which is deprecated.
Looking on PHP.net I thought I could just get away and change to preg_match()

But I get errors with the regular expressions or they fail!!

Here are two examples:

function input_login() {
    if (ereg("[^-_@\.A-Za-z0-9]", $input_value)) { // WORKS
    // if (preg_match("[^-_@\.A-Za-z0-9]", $input_value)) { // FAILS
        echo "is NOT alphanumeric with characters - _ @ . allowed";
    }
}

// validate email
function validate_email($email) {
    // return eregi("^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$", $email); // FAILS
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

铜锣湾横着走 2024-09-15 22:21:00

您忘记了分隔符:

if (preg_match("/[^[email protected]]/", $input_value))

此外,点不需要在字符类中转义。

对于验证函数,您需要使用 i 修饰符使正则表达式不区分大小写:

return preg_match('/^[_.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i', $email)

You forgot the delimiters:

if (preg_match("/[^[email protected]]/", $input_value))

Also, the dot doesn't need to be escaped inside a character class.

For your validation function, you need to make the regex case-insensitive by using the i modifier:

return preg_match('/^[_.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i', $email)
窝囊感情。 2024-09-15 22:21:00

我无法再抑制人们根本不喜欢我的 [email  ;protected] 电子邮件地址(我只更改了右侧部分)。这是一个绝对正常的地址,有效、简短且易于输入。简直就是人家不喜欢啊!无法使用该邮件在任何页面上注册。

那么,为什么不友善地使用 PHP 过滤器扩展来验证邮件或使用 PCRE,这绝对允许使用所有有效的电子邮件(仅排除 @[] 的电子邮件):

/^[^@]+@(?:[^.]+\.)+[A-Za-z]{2,6}$/

感谢您保存我的电子邮件,这是一个死亡物种!

I can't suppress the suspicion anymore that people simply don't like my [email protected] email address (I changed the right part only). It is an absolutely normal address, it's valid, short and easy to type. Simply people don't like it! One cannot register on any page using that mail.

So, why don't be nice and use PHPs Filter extension to verify the mail or to use a PCRE, which definitely allows all valid emails in use (excluding only the @[] ones):

/^[^@]+@(?:[^.]+\.)+[A-Za-z]{2,6}$/

Thanks for saving my email, it's a dieing species!

2024-09-15 22:21:00

尝试 preg_match("/[^-_@\.A-Za-z0-9]/", $input_value)

try preg_match("/[^-_@\.A-Za-z0-9]/", $input_value)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文