preg_replace Remove comment text in content

In post content, i insert a text like below

 abc acb acb acb
<!--REMOVE--> text to remove <!--ENDREMOVE-->
 abc acb acb acb
 abc acb acb acb
<!--REMOVE--> text to remove <!--ENDREMOVE-->
 abc acb acb acb
 abc acb acb acb
<!--REMOVE--> text to remove <!--ENDREMOVE-->
 abc acb acb acb

I want to get only

Read More
abc acb acb acb
abc acb acb acb
abc acb acb acb
abc acb acb acb
abc acb acb acb
abc acb acb acb

And i run this code

 function remove($content){
    preg_match_all("/<!--REMOVE-->.*<!--ENDREMOVE-->/", $content, $matches);
    var_dump($matches);
    $content= preg_replace("/<!--REMOVE-->.*<!--ENDREMOVE-->/", '', $content);

    return $content;
 }
 add_filter('the_content', 'remove', 1);

but it does not work. What is the problem ?

The real result from above code is

abc acb acb acb
abc acb acb acb

And var_dump is one result, not 3 results

array
    0 => <!--REMOVE--> text to remove <!--ENDREMOVE-->
         abc acb acb acb
         abc acb acb acb
         <!--REMOVE--> text to remove <!--ENDREMOVE-->
         abc acb acb acb
         abc acb acb acb
         <!--REMOVE--> text to remove <!--ENDREMOVE-->

The right way is

array
   0 => <!--REMOVE--> text to remove <!--ENDREMOVE-->

   1 => <!--REMOVE--> text to remove <!--ENDREMOVE-->

   2 => <!--REMOVE--> text to remove <!--ENDREMOVE-->

Related posts

1 comment

  1. The problem you are having with your code is this line:

    $conten = preg_replace("/<!--REMOVE-->.*<!--ENDREMOVE-->/", '', $content);
    

    $conten is assigned, but $content is returned.

    function remove( $content ) {
        return preg_replace( '/<!--REMOVE-->.*<!--ENDREMOVE-->/', '', $content );
    }
    

    After question edit:

    The real result from above code is

    abc acb acb acb
    abc acb acb acb
    

    .* is greedy. It finds all matches up to the last <!--ENDREMOVE-->.

    .*? is not greedy. It finds all matches up to the first <!--ENDREMOVE-->.

    Use this function:

    function remove( $content ) {
        return preg_replace( '/<!--REMOVE-->.*?<!--ENDREMOVE-->/', '', $content );
    }
    

Comments are closed.