RegEx从PHP 7.4开始失败,在7.3中工作



有什么想法吗?为什么这个preg_match可以工作到PHP7.2,但在7.3+时失败了?

$word = 'umweltfreundilch'; //real life example :/
preg_match('/^(?U)(.*(?:[aeiouyäöü])(?:[^aeiouyäöü]))(?X)(.*)$/u', $word, $matches);
var_dump($matches);

警告:preg_match((:编译失败:(?或(?-之后的字符无法识别

PHP 7.2及以下版本的输出:

array(3) {
[0]=>
string(16) "umweltfreundilch"
[1]=>
string(2) "um"
[2]=>
string(14) "weltfreundilch"
}

RegEx似乎还好,不是吗
https://regex101.com/r/LGdhaM/1

在PHP 7.3及更高版本中,Perl兼容正则表达式(PCRE(扩展升级为PCRE2。

PCRE2语法文档没有将(?X)列为可用的内联修饰符选项。以下是支持的选项:

(?i)            caseless
(?J)            allow duplicate named groups
(?m)            multiline
(?n)            no auto capture
(?s)            single line (dotall)
(?U)            default ungreedy (lazy)
(?x)            extended: ignore white space except in classes
(?xx)           as (?x) but also ignore space and tab in classes
(?-...)         unset option(s)
(?^)            unset imnsx options

但是,您实际上可以在后面的分隔符后面使用X标志:

preg_match('/^(?U)(.*[aeiouyäöü][^aeiouyäöü])(.*)$/Xu', $word, $matches)

请参阅PHP 7.4演示。

要取消(?U)效果,您可以使用两个选项之一:(?-U)内联修饰符,如中

preg_match('/^(?U)(.*[aeiouyäöü][^aeiouyäöü])(?-U)(.*)$/u', $word, $matches);
//                                           ^^^^^

或者,将受影响的模式封装到(?U:...)修饰符组中:

preg_match('/^(?U:(.*[aeiouyäöü][^aeiouyäöü]))(.*)$/u', $word, $matches);
//            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        

在preg_match((中查看有关PHP 7.3+中regex处理更改的更多信息:编译失败:字符类中偏移量处的无效范围。

最新更新