如何在 preg_replace 中的模式中使用正则表达式特殊字符
how to use regex special characters in pattern in preg_replace
我正在尝试将 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);
字符串没有被修改。参见 the PHP demo。这里的正则表达式分隔符是 /
,因此它作为第二个参数传递给 preg_quote
.
请注意,[^a-z^A-Z]
匹配除 ASCII 字母 和 ^
之外的任何字符,因为您在字符 [=44] 中添加了第二个 ^
=].我将 [^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';
我正在尝试将 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);
字符串没有被修改。参见 the PHP demo。这里的正则表达式分隔符是 /
,因此它作为第二个参数传递给 preg_quote
.
请注意,[^a-z^A-Z]
匹配除 ASCII 字母 和 ^
之外的任何字符,因为您在字符 [=44] 中添加了第二个 ^
=].我将 [^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';