Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/245.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 preg_replace-正则表达式(删除标记)_Php_Expression_Preg Replace - Fatal编程技术网

Php preg_replace-正则表达式(删除标记)

Php preg_replace-正则表达式(删除标记),php,expression,preg-replace,Php,Expression,Preg Replace,我对令牌感到满意,并希望去除所有不以test开头的令牌。例如,我有以下内容: $content = 'Hello [test:username]. What are you [token:name]'; $string = preg_replace('/\[test(.*)\]/', '', $content); 此操作有效,但用空字符串替换以test开头的所有标记。我想要相反的不以测试开始,并替换所有其他。我应该如何更改正则表达式。我想在preg_replace之后得到这个结果: $cont

我对令牌感到满意,并希望去除所有不以test开头的令牌。例如,我有以下内容:

$content = 'Hello [test:username]. What are you [token:name]';
$string = preg_replace('/\[test(.*)\]/', '', $content);
此操作有效,但用空字符串替换以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:...]

查看regex文档,特别是在模式开始时使用
^
,不客气。很高兴它帮助了你@user3421014我还为未来的用户添加了一个解释