views:

34

answers:

3

I'm using preg_replace_callback to substitute particular tokens within the string. But apart from actual token I need to know as well whether that token was first, second or third in a subject string. Is there any way to access that info?

I found an argument $count in preg_replace_callback definition (http://php.net/manual/en/function.preg-replace-callback.php), which counts replacements, but I'm not sure if it is accessible from within callback. Any example of the usage in described context?

+1  A: 

You can always create a non-local variable to keep the count.

KennyTM
Do not like to leave pieces of inner logic outside :) But that was nice too. Amazing how many different solutions exist once you step back from "impossible" task and ask questions.
jayarjo
+1  A: 

The $count out variable is only set after all the replacements are done. Instead, try a static variable:

function repl($matches) {
    static $count = 0;
    ++$count;
    ...
}
preg_replace_callback('/.../', 'repl', $haystack);
outis
So obvious :) Thanks.
jayarjo
+1  A: 

With php 5.3+ you can also use a closure (instead of a global or static variable)

$counter = 0
preg_replace_callback('/.../', function($matches) use(&$counter) {
  ++$counter;
  ...
  },  $haystack
);
VolkerK
5.3 is cool, although vast majority of hosting servers still run lower versions, or even - 4 =-O
jayarjo