问题
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:
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);
回答2:
You can always create a non-local variable to keep the count.
回答3:
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
);
来源:https://stackoverflow.com/questions/2482493/can-i-somehow-know-which-replacement-is-taking-place-from-within-a-callback-of-p