如何从字符串中删除所有匹配的部分?

时间:2018-06-21 11:17:51

标签: php regex loops

这是我的代码:

$tags_specified_pattern = "/\[(.+?)\]/";
preg_match_all($tags_specified_pattern, $q, $matches);
if ( count($matches[1]) ){
    I need to remove all matched parts form $q
}

这里是一个例子:

$q = "This is [tag1] tag1 and this is [tag2] tag2";

这是预期的结果:

This is tag1 and this is tag2

任何想法我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以使用 preg_replace

<?php
$pattern = '/\\[(.+?)\\]/';
$replacement = '';
$subject = 'This is [tag1] tag1 and this is [tag2] tag2';
echo preg_replace($pattern, $replacement, $subject, -1 );
?>