如何在 preg_replace 模式中使用正则表达式特殊字符 [英] how to use regex special characters in pattern in preg_replace

查看:40
本文介绍了如何在 preg_replace 模式中使用正则表达式特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 2.0 替换为堆栈,

I am trying to replace 2.0 to stack,

但以下代码将 2008 替换为 2.08

but the following code replace 2008 to 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 并确保将正则表达式分隔符作为第二个参数传递:

Use preg_quote and make sure you pass the regex delimiter as the second argument:

$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.

The string is not modified. See the PHP demo. The regex delimiter here is /, thus it is passed as the 2nd parameter to preg_quote.

请注意,[^az^AZ] 匹配除 ASCII 字母 ^ 以外的任何字符,因为您添加了第二个 ^ 在字符类中.我将 [^a-z^A-Z] 改为 [^a-zA-Z].

Note that [^a-z^A-Z] matches any chars but ASCII letters and ^ since you added the second ^ in the character class. I changed [^a-z^A-Z] to [^a-zA-Z].

此外,开头的捕获组可以替换为单个后视,(?<!\S),它将确保您的匹配仅出现在字符串开头或之后空格.

Also, the capturing group at the start may be replaced with a single lookbehind, (?<!\S), it will make sure your match occurs only at the string start or after a whitespace.

如果您希望在字符串的末尾也匹配,请替换 (?=[^a-zA-Z])(这需要一个字符,而不是紧靠右侧的字母当前位置)和 (?![a-zA-Z])(需要一个字符而不是字母 或字符串结尾 紧接在当前位置的右侧位置).

If you expect to also match at the end of the string, replace (?=[^a-zA-Z]) (that requires a char other than a letter immediately to the right of the current location) with (?![a-zA-Z]) (that requires a char other than a letter or end of string immediately to the right of the current location).

所以,使用

$pattern = '/(?<!\S)' . preg_quote($tag, '/') . '(?![a-zA-Z])/i';

另外,考虑使用明确的词边界

Also, consider using unambiguous word boundaries

$pattern = '/(?<!\w)' . preg_quote($tag, '/') . '(?!\w)/i';

这篇关于如何在 preg_replace 模式中使用正则表达式特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆