Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在preg_replace中使用模式中的正则表达式特殊字符_Php_Regex_Preg Replace - Fatal编程技术网

Php 如何在preg_replace中使用模式中的正则表达式特殊字符

Php 如何在preg_replace中使用模式中的正则表达式特殊字符,php,regex,preg-replace,Php,Regex,Preg Replace,我正在尝试将2.0替换为stack 但以下代码将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); 使用并确保将re

我正在尝试将2.0替换为stack

但以下代码将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);
使用并确保将regex分隔符作为第二个参数传递:

$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);
字符串未被修改。看见这里的正则表达式分隔符是
/
,因此它作为第二个参数传递给
preg\u quote

请注意,
[^a-z^a-z]
匹配除ASCII字母和
^
之外的任何字符,因为您在字符类中添加了第二个
^
。我将
[^a-z^a-z]
更改为
[^a-zA-z]

此外,开始处的捕获组可能会被替换为单个lookback,
(?),它将确保您的匹配只发生在字符串开始处或空白之后

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

所以,使用

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

$pattern='/(?你说的
是什么意思?我正在尝试将2.0替换为stack,
?我在字符串中没有看到
stack
。你想匹配和替换什么?你的模式将是
(\s| ^)2.0(?=[^a-z^a-z])
当前字符串中的哪个将匹配一个空格、2、由点和0引起的任何字符。我将使用反斜杠替换点
$tag='2.\0';
$pattern = '/(?<!\w)' . preg_quote($tag, '/') . '(?!\w)/i';