Is there a way to pass another parameter in the preg_replace_callback callback function?
It is hard to pass arguments to callbacks, but instead of this:
return preg_replace_callback($this->reg, 'Foo::Bar', $this->string);
You could make Bar()
not static, and use this:
return preg_replace_callback($this->reg, array($this, 'Bar'), $this->string);
Then the callback function will be able to see $this
See 'callback' in Pseudo-types and variables
Also in PHP >=5.3 you could use anonymous functions/closures to pass other data to callback functions.
I got stuck while trying to pass an argument (extra parameter) to a callback with the create_function() and call_user_function() methods.
This is for reference:
<?php$pattern = "/([MmT][a-z]*)/";$string = "Mary is a naughty girl because she took all my animals.";$kill = "Mary";echo preg_replace_callback($pattern, function($ma) use ($kill) { foreach ($ma as $m){ if ($m == $kill){ return "Jenny"; } return "($m)"; }}, $string);echo "\n";?>
$ php preg_replace_callback.php Jenny is a naughty girl because she took all (my) ani(mals).
yes I use something like this to set and unset a changing variable so that it is available to the callback function and you don't need the newer php to do it:
foreach ($array as $key) { $this->_current_key = $key; preg_replace_callback($regex, array($this, '_callback'), $content); unset($this->_current_key);}
then in the callback function $this->_current_key is available:
function _callback ($match) { //use the key to do something new_array[$key] = $match[0]; //and still remove found string return '';}