如何解决自PHP 7.4起,RegEx在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)扩展was upgraded到PCRE2。
PCRE2 syntax documentation并未将(?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 demo。
要取消(?U)
效果,可以使用以下两个选项之一:(?-U)
内联修饰符,例如in
preg_match('/^(?U)(.*[aeiouyäöü][^aeiouyäöü])(?-U)(.*)$/u',$matches);
// ^^^^^
或者,将受影响的模式包含在(?U:...)
修饰符组中:
preg_match('/^(?U:(.*[aeiouyäöü][^aeiouyäöü]))(.*)$/u',$matches);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
在preg_match(): Compilation failed: invalid range in character class at offset中了解有关PHP 7.3+中的正则表达式处理更改的更多信息。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。