Search code examples
phppreg-replace-callback

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


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?


Solution

  • 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);