我想使用函数preg_replace
替换PHP中 [test] 内的所有单词(例如 test )。< / p>
我现在就这样做了:
$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 />";
答案 0 :(得分:0)
怎么样:
$txt = preg_replace('#(?:^|[^\[])'.$word.'(?:[^\]]|$)#i', '['.$word.']', $txt);