I'm using preg_replace_callback to substitute particular开发者_StackOverflow中文版 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?
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);
You can always create a non-local variable to keep the count.
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
);
精彩评论