Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/240.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 正则表达式匹配不在[and]内的单词_Php_Regex - Fatal编程技术网

Php 正则表达式匹配不在[and]内的单词

Php 正则表达式匹配不在[and]内的单词,php,regex,Php,Regex,我想在PHP中使用函数preg\u replace用[test]替换[and]之外的所有单词(如test) 我现在已经这样做了: $txt = preg_replace('#([^\[])' . $word . '([^\]])#i', '[' . $word . ']', $txt); 但模式与测试不匹配 这是我的测试: $txt = 'atesta, test, [test], [atesta]'; $pattern = '#(?:^|[^\[])test(?:[^\]]|$)#i'; $

我想在PHP中使用函数
preg\u replace
用[test]替换[and]之外的所有单词(如test)

我现在已经这样做了:

$txt = preg_replace('#([^\[])' . $word . '([^\]])#i', '[' . $word . ']', $txt);
但模式与测试不匹配

这是我的测试:

$txt = 'atesta, test, [test], [atesta]';
$pattern = '#(?:^|[^\[])test(?:[^\]]|$)#i';
$replace = '[test]';
echo "$txt<br />";
$txt = preg_replace($pattern, $replace, $txt);
echo "$txt<br />";
$txt = preg_replace($pattern, $replace, $txt);
echo "$txt<br />";
$txt='atesta,test,[test],[atesta];
$pattern='#(?:^ |[^\[])测试(?:[^\].$)#i';
$replace='[test]';
回显“$txt
”; $txt=preg_replace($pattern,$replace,$txt); 回显“$txt
”; $txt=preg_replace($pattern,$replace,$txt); 回显“$txt
”;
那么:

$txt = preg_replace('#(?:^|[^\[])'.$word.'(?:[^\]]|$)#i', '['.$word.']', $txt);

请注意,按照现在的书写方式,单词的前后必须有一个字符:行首或行尾的单词将不匹配。请注意,此处不需要转义方括号
[^[]
是可以的,因为
[
在类中没有意义;
[^]
是可以的,因为类必须至少包含一个字符,所以
[^]
单独无效,导致
]
没有特殊意义(类似于类开头或结尾的
-
没有意义)您希望每个测试字符串的结果是什么。那么没有括号的
atesta
呢?刚刚更新了我的帖子,atesta failshi,部分有效,因为它对[test]有效,但我希望它对[test1,test2]有效@Bouki:请用尽可能多的测试用例更新你的问题。刚刚更新了我的帖子,事实是我可以有[atesta](测试不直接在内部[和],但前后可能会有一些东西)