Question

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

Was it helpful?

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.

OTHER TIPS

You need to share a $count variable between both variable scopes, for example by using a variable alias:

$callback = function($matches) use (&$count) {
    $count++;
    return sprintf("<%d:%s>", $count, $matches[0]);
};

echo preg_replace_callback($pattern, $callback , $subject, $limit = -1, $count);

Before invoking, $count is equal to 0. After invoking $count is set to the number of replacements done. In between you can count up in your callback. You can also set to zero again when calling another time.

See it in action

See http://php.net/preg_replace_callback

$repled     = 0;
function pregRepler($matches)
{
    * do something
    global $repled;
    $repled++;
}

$str = preg_replace_callback($reg_exp,'pregRepler',$str);

Just count from a global variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top