Skip to content
Advertisement

How to know the match count in preg_replace_callback – PHP

I have this code in php -:

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.??

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement