为什么 PHP 函数 preg_replace('/a*?/', '!', 'a') 给出 '!!!'但 '/a*/' 给出 '!!'

问题描述 投票:0回答:1

注意到 PHP 函数:

preg_replace('/a*?/', '!', 'a') 

给出

'!!!'
但是:

 preg_replace('/a*/', '!', 'a') 

给予

'!!'

我想我明白为什么

'!!'
,因为 in 匹配空子字符串,但不明白为什么
'!!!'

如果我匹配子字符串错误,请纠正我,并解释或给出链接原因

'!!!'

php regex preg-replace
1个回答
1
投票

要了解该行为,您可以使用

preg_match_all()

贪心搜索:

preg_match_all('/a*/', 'a', $matches);
var_export($matches[0]);

输出:

array (
  0 => 'a',
  1 => '',
)

此处开头不匹配。

非贪婪搜索:

preg_match_all('/a*?/', 'a', $matches);
var_export($matches[0]);

输出:

array (
  0 => '',
  1 => 'a',
  2 => '',
)

开头和结尾都匹配。

© www.soinside.com 2019 - 2024. All rights reserved.