我有令牌的内容,并且想要删除所有不以测试开头的令牌。例如,我有内容:
$content = 'Hello [test:username]. What are you [token:name]';
$string = preg_replace('/\[test(.*)\]/', '', $content);
这项工作,但用空字符串替换所有以测试开头的标记。我希望与测试 无法启动相反,并替换所有其他内容。我应该如何改变正则表达式。我想在preg_replace之后得到这个结果:
$content = 'Hello [test:username]. What are you';
答案 0 :(得分:1)
您可以使用以下正则表达式
(?:\[test:[^]]+\])(*SKIP)(*F)|(?:\[\w[^]]+\])
所以你的代码看起来像
preg_replace('/(?:\[test:[^]]+\])(*SKIP)(*F)|(?:\[\w[^]]+\])/', '', $content);
<强>解释强>
(?:\[test:[^]]+\]) // Will capture a group of tokens that have same
pattern like as [test:...]
(*SKIP)(*F) // This is supported by PCRE to skip the above captured group
|(?:\[\w[^]]+\]) // This'll capture rest of the group that doesn't
contains pattern like as [test:...]