Can I somehow know which replacement is taking place from within a callback of preg_replace_callback?

北慕城南 提交于 2019-12-11 12:52:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!