phpcountingpreg-replace-callback

Keep track of replacement tally with preg_replace_callback()


I have this code:

function pregRepler($matches)
{
    * do something
}
 
$str = preg_replace_callback($reg_exp, 'pregRepler', $str);

When in function pregRepler, I would want to know the current match number like if it is the first match or the second or anything.

How do I do it?


Solution

  • Try something like this:

    function pregRepler($matches) {
        static $matchcount = 0;
        // do stuff
        $matchcount++;
    }
    

    This works better with an anonymous function, as I mentioned in my answer to your other question, as this will avoid problems if you have multiple calls to preg_replace_callback.