我正在尝试将 2.0 替换为堆栈,
但以下代码将 2008 替换为 2.08
以下是我的代码:
$string = 'The story is inspired by the Operation Batla House that took place in 2008 ';
$tag = '2.0';
$pattern = '/(\s|^)'.($tag).'(?=[^a-z^A-Z])/i';
echo preg_replace($pattern, '2.0', $string);
使用preg_quote
并确保将正则表达式分隔符作为第二个参数传递:
$string = 'The story is inspired by the Operation Batla House that took place in 2008 ';
$tag = '2.0';
$pattern = '/(\s|^)' . preg_quote($tag, '/') . '(?=[^a-zA-Z])/i';
// ^^^^^^^^^^^^^^^^^^^^^
echo preg_replace($pattern, '2.0', $string);
字符串未修改。请参阅PHP 演示。这里的正则表达式分隔符是/
,因此它作为第二个参数传递给preg_quote
.
请注意,[^a-z^A-Z]
匹配除 ASCII 字母之外的任何字符,并且^
因为您^
在字符类中添加了第二个字符。我换[^a-z^A-Z]
到[^a-zA-Z]
。
此外,开头的捕获组可能会替换为单个后视, (?<!\S)
,它将确保您的匹配仅发生在字符串开头或空格之后。
如果你希望也匹配字符串的结尾,替换(?=[^a-zA-Z])
(即需要比立即到当前位置的右侧的字母以外的字符)与(?![a-zA-Z])
(需要除字母以外的字符或字符串的结尾立即向右当前位置)。
所以,使用
$pattern = '/(?<!\S)' . preg_quote($tag, '/') . '(?![a-zA-Z])/i';
另外,考虑使用明确的词边界
$pattern = '/(?<!\w)' . preg_quote($tag, '/') . '(?!\w)/i';
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句