如何将 PHP 的 eregi 更改为 preg_match

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1374881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:16:08  来源:igfitidea点击:

How to change PHP's eregi to preg_match

phpemailpcreposix-ere

提问by JasonDavis

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

可能的重复:
如何在 PHP 中将 ereg 表达式转换为 preg?

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 functionwhich php.net says is now a depreciated function and I should use preg_matchinstead, simply replacing erei with preg_match does not work, can someone show me how to make it work?

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

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';
    }
}

回答by Amber

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

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

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.

您最初的尝试无效的原因是它试图^用作分隔符,但(显然)^在正则表达式的末尾找不到匹配项。

回答by Peter Bailey

You will need to change three things

你需要改变三件事

  1. need to add pattern delimiters (can be any character, but most commonly a forward slash)
  2. [[:alnum:]] will need to be replaced with the PCRE equivalent
  3. The "i" in "eregi" means case-insensitive, which PCRE does with a flag, specifically the iflag.
  1. 需要添加模式分隔符(可以是任何字符,但最常见的是正斜杠)
  2. [[:alnum:]] 将需要替换为 PCRE 等效项
  3. "eregi" 中的 "i" 表示不区分大小写,PCRE 使用标志,特别是i标志。

Otherwise, the rest looks PCRE compatible (yes, that's kind of redundant =P)

否则,其余部分看起来与 PCRE 兼容(是的,这有点多余 =P)

"/^[a-z0-9][a-z0-9_.-]*@[a-z0-9.-]+\.[a-z]{2,4}$/i"