[英]regex match a word not inside [ and ]
我想使用preg_replace
函数在PHP中用[test]替换不在[和]内的所有单词(例如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 = preg_replace('#(?:^|[^\[])'.$word.'(?:[^\]]|$)#i', '['.$word.']', $txt);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.