Sachin
Sachin

Reputation: 113

Ignore certain matches in preg_replace

Please find php string below :

$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 .... ]';

I want to remvoe [ok i can remove it] and [ok i can remove it too] but I want to retain [caption .... ] in the string using preg_replace. Current I am using following which is removing all with [ ]

$return = preg_replace( array('~\[.*]~'), '', $b );

kindly guide.

Upvotes: 1

Views: 322

Answers (1)

Toto
Toto

Reputation: 91430

For this kind of job, I'd use preg_replace_callback like this:

$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";

Output:

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

Upvotes: 1

Related Questions