忽略preg_replace中的某些匹配项

时间:2016-04-01 06:16:54

标签: preg-replace

请在下面找到php字符串:

private static int suicide (List<Integer> list, int step) {

        ListIterator<Integer> itr = list.listIterator();

        while(itr.hasNext()&& list.size() != 1){

            if((itr.nextIndex()+1) % step == 0) {
                System.out.println(itr.previousIndex()+1);
                itr.next();
                itr.remove();
                itr.next();
            }
            else {
                itr.next();
            }

            if(!itr.hasNext() ){

                itr=list.listIterator();
            }
        }
        return 0;
    }

我想要remvoe [确定我可以删除它]和[确定我也可以删除它]但我想在preg_replace中保留字符串中的[caption ....]。 当前我正在使用以下内容,即使用[]

删除所有内容
$string = 'hi this is testing [ok i can remove it] and
then [ok i can remove it too] and then I want to spare [caption .... ]';
善意的指导。

1 个答案:

答案 0 :(得分:0)

对于这类工作,我会像这样使用preg_replace_callback

$string = 'hi this is testing [ok i can remove it] and then [ok i can remove it too] and then I want to spare [caption .... ]';
$return = preg_replace_callback(
           '~\[[^\]]*\]~', 
           function($m) {
               if (preg_match('/\bcaption\b/', $m[0]))
                   return $m[0];
               else
                   return '';
           }, 
           $string);
echo $return,"\n";

<强>输出:

hi this is testing  and then  and then I want to spare [caption .... ]