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

标签 php regex preg-match

有什么想法为什么这个 preg_match 可以在 PHP7.2 上运行但在 7.3+ 上失败?

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

Warning: preg_match(): Compilation failed: unrecognized character after (? or (?-


PHP 7.2 及以下输出:
array(3) {
  [0]=>
  string(16) "umweltfreundilch"
  [1]=>
  string(2) "um"
  [2]=>
  string(14) "weltfreundilch"
}
正则表达式似乎没问题,不是吗?
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)效果,您可以使用以下两个选项之一:a (?-U)内联修饰符,如
preg_match('/^(?U)(.*[aeiouyäöü][^aeiouyäöü])(?-U)(.*)$/u', $word, $matches);
//                                           ^^^^^
或者,将受影响的模式包含在 (?U:...) 中修饰符组:
preg_match('/^(?U:(.*[aeiouyäöü][^aeiouyäöü]))(.*)$/u', $word, $matches);
//            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        
preg_match(): Compilation failed: invalid range in character class at offset 中查看有关 PHP 7.3+ 中正则表达式处理更改的更多信息.

关于php - RegEx 从 PHP 7.4 开始失败,在 7.3 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63826129/

相关文章:

regex - 将正则表达式拆分为 2 个捕获组

php - 无法使用 Behat Mink 扩展框架在输入字段中附加文件(csv 文件)

php - mysql中的getdate()

java - 试图用 Java 理解正则表达式中的 "Capturing groups"

php - 编译失败 : nothing to repeat at offset 6

php - 主机名上的 preg_match

php - preg_match : number-alphabets and commas only

php fputcsv 在 CSV 中使用分号分隔符

javascript - 如何使用 jQuery 的 ajax 方法将 json 数组发送到 PHP?

python - 正则表达式为英语和俄语提供不同的结果