Search code examples
preg-replace-callback

How to use preg_replace_callback


I am trying to replace the 2nd occurrence of the $target_str.

If someone could explain how preg_replace_callback works I would appreciate it. I don't understand the function($match) part. How do I set it so it matches the 2nd occurrence and only replaces that string?

I have the code (but it doesn't work as I want it to).

$replacement_params['target_str'] = "[\n]"; $replacement_params['replacement_str'] = "\n<ads media=googleAds1 />\n"; $target_str = $this->params['target_str']; $replacement_str = $this->params['replacement_str']; $num_matches;

$i = 0;
$new_text = preg_replace_callback("/".$target_str."/U", 
            function ( $match ) {
                if ( $i === 1 ) {
                    return $replacement_str;
                } else {
                    return $match[0];
                }
                $i++;
            } , $article_text, 1, $num_matches );

Solution

  • Updated

    Using built-in counter variable of preg_replace_callback:

    $new_text = preg_replace_callback("/$target_str/U", 
                    function($matches) use (&$count, $replacement_str)
                    {
                        $count++;
                        return ($count == 2) ? $replacement_str : $matches[0];
                    } , $article_text, -1, $count);