php - 正则表达式自 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)
内联修饰符,如 in
preg_match('/^(?U)(.*[aeiouyäöü][^aeiouyäöü])(?-U)(.*)$/u', $word, $matches);
// ^^^^^
或者,将受影响的模式包含在(?U:...)
修饰符组中:
preg_match('/^(?U:(.*[aeiouyäöü][^aeiouyäöü]))(.*)$/u', $word, $matches);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
在 preg_match() 中查看有关 PHP 7.3+ 中正则表达式处理更改的更多信息:编译失败:offset 处的字符类中的无效范围。
推荐阅读
- ios - 如何从@propertywrapper 中公开闭包?
- javascript - 使用 for 循环 (JS) 在变量名末尾分配索引 (i) 值
- json - Circe asJson 不编码抽象基类的属性
- reactjs - React Material UI 扩展面板禁用光标指针
- swift - 有没有办法在 SwiftUI 中向 Lottie 动画开关添加动作
- python - 如何更改 Django 管理员用户更改页面选项卡的标题?
- html - 如何在所有屏幕尺寸上保持 SVG 的波形
- javascript - Python 和 Node 之间的 Diffie-Hellman 密钥交换失败并出现错误提供的密钥太大
- python - pygithub - 接收特定分支的所有提交
- tensorflow - 如何仅为正则化损失编写自定义指标?