Php preg_replace - 正则表达式(删除标记)
Php preg_replace - regular expression (remove tokens)
我对令牌很满意,想去除所有不以 test 开头的令牌。例如我有内容:
$content = 'Hello [test:username]. What are you [token:name]';
$string = preg_replace('/\[test(.*)\]/', '', $content);
这行得通,但用空字符串替换所有以 test 开头的标记。我想要相反 不启动 与 test 并替换所有其他。我应该如何更改正则表达式。我想在 preg_replace:
之后得到这个结果
$content = 'Hello [test:username]. What are you';
您可以使用以下正则表达式
(?:\[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:...]
我对令牌很满意,想去除所有不以 test 开头的令牌。例如我有内容:
$content = 'Hello [test:username]. What are you [token:name]';
$string = preg_replace('/\[test(.*)\]/', '', $content);
这行得通,但用空字符串替换所有以 test 开头的标记。我想要相反 不启动 与 test 并替换所有其他。我应该如何更改正则表达式。我想在 preg_replace:
之后得到这个结果$content = 'Hello [test:username]. What are you';
您可以使用以下正则表达式
(?:\[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:...]