与 POSIX 正则表达式的不同

自 PHP 5.3.0起, POSIX 正则表达式扩展被废弃。在 POSIX 正则和 PCRE 正则之间有一些不同,本页列出了在转向PCRE 时最显著的需要知道的不同点。

  1. PCRE 函数需要模式以分隔符闭合。
  2. 不像POSIX,PCRE 扩展没有专门用于大小写不敏感匹配的函数。取而代之的是,支持使用i (PCRE_CASELESS) 模式修饰符完成同样的工作。 其他模式修饰符同样可用于改变匹配策略。
  3. POSIX 函数从最左面开始寻找最长的匹配,但是 PCRE 在第一个合法匹配后停止。如果字符串 不匹配这没有什么区别,但是如果匹配,两者在结果和速度上都会有差别。 为了说明这个不同, 考虑下面的例子(来自Jeffrey Friedl 的《精通正则表达式》一书)。 使用模式 one(self)?(selfsufficient)? 在字符串oneselfsufficient 上匹配,PCRE 会匹配到oneself,但是使用 POSIX,结果将是整个字符串 oneselfsufficient。 两个子串都匹配原始字符串,但是 POSIX 将 最长的作为结果。

函数对照表
POSIX PCRE
ereg_replace() preg_replace()
ereg() preg_match()
eregi_replace() preg_replace()
eregi() preg_match()
split() preg_split()
spliti() preg_split()
sql_regcase() 无对等函数

User Contributed Notes

cdragon at dracoventions dot com 21-Jul-2013 12:48
In regards to the previous comment that says "there are several other differences including different meaning for the symbols  ( [ different rules for which symbols need escaping", as far as I can tell from reading
http://www.tin.org/bin/man.cgi?section=7&topic=regex
there are absolutely no "other differences" except in what the man page calls "Obsolete  ("basic'')  regular  expressions".  However, PHP doesn't appear to use the obsolete form of expressions in its POSIX functions.

PCRE even supports all of the POSIX named character classes such as [:space:].
jasen at treshna dot com 27-Oct-2011 12:11
there are several other differences

including different meaning for the symbols  ( [
different rules for which symbols need escaping (they can't be the same as both standard posix and extended posix)

you should read the full documentation for PCRE before chaging any posix regex to use pcre.