Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

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-->
share|improve this question

1 Answer 1

up vote 1 down vote accepted

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 );
}
share|improve this answer
    
i have updated my questions, please check –  Quang Trung Nguyen Oct 22 '13 at 4:26
    
See the edit ..... –  Charles Clarkson Oct 22 '13 at 4:51
    
yeaah, thank you. It worked. –  Quang Trung Nguyen Oct 22 '13 at 4:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.