PHP 正则表达式非贪婪匹配在某些服务器上无法正常工作



我有以下最小的例子,它在本地服务器(WAMP,PHP 7.3.7(和使用PHP 7.3.27的生产服务器上表现不同。本地服务器上的结果对我来说似乎是错误的,因为懒惰修饰符被忽略了。结果也与我尝试过的所有regex测试程序相冲突。

示例代码:

<?php
header('Content-Type: text/plain; charset=utf-8');
$input = <<<EOT
John Smith
John Smith (123)
John Smith (123) (456)
EOT;

preg_match_all('/(.+?)(?:s((d+)))?$/m', $input, $matches_defines);
print_r($matches_defines);
?>

本地环境中的结果:

Array
(
[0] => Array
(
[0] => John Smith
[1] => John Smith (123)
[2] => John Smith (123) (456)
)
[1] => Array
(
[0] => John Smith
[1] => John Smith (123)
[2] => John Smith (123)
)
[2] => Array
(
[0] => 
[1] => 
[2] => 456
)
)

生产环境中的结果:

Array
(
[0] => Array
(
[0] => John Smith
[1] => John Smith (123)
[2] => John Smith (123) (456)
)
[1] => Array
(
[0] => John Smith
[1] => John Smith
[2] => John Smith (123)
)
[2] => Array
(
[0] => 
[1] => 123
[2] => 456
)
)

有人能告诉我这种差异是从哪里来的吗?当地环境可以做出什么调整来纠正这种差异?

好的,在这里回答我自己的问题:这是一个Windows/Linux行结束问题。

本地服务器上的regex失败,因为在文本中,每个右括号后面都有一个r。因此,右括号不是一行的末尾,在该行的末尾($(之前还有一个附加字符r。(来源(

这可以通过稍微修改一下的regex:/(.+?)(?:s((d+)))?s*$/m来修复。注意末尾的s*。这与行末尾的r相匹配(如果它在那里的话(。

最新更新