1

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

sanchitkhanna26
  • 2,143
  • 8
  • 28
  • 42
  • 1
    I know its an old question but since PHP 5.1.0 a "count" variable has been added. You can use it to get the count. `preg_replace_callback ($regex, callback_function, $subject, $limit, &$count)` – Kalimah Jan 06 '19 at 11:07

3 Answers3

7

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.

Community
  • 1
  • 1
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
2

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

M8R-1jmw5r
  • 4,896
  • 2
  • 18
  • 26
0
$repled     = 0;
function pregRepler($matches)
{
    * do something
    global $repled;
    $repled++;
}

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

Just count from a global variable.

Luceos
  • 6,629
  • 1
  • 35
  • 65