Extra params for callback used with preg_replace_callback
Posted: Sat Sep 30, 2006 4:35 pm
I am creating a string using a template like thisand an array like thisinto a result like this
I am using preg_replace_callback to achieve this. Problem is I need to pass said array to callback function in addition to the match passed by preg_replace_callback() itself. How can I do this without global or class variables?
Simplified Recreation:
Solution doesn't necessary have to use preg_replace_callback() at all
Code: Select all
$0 is the first element and $1 is the secondCode: Select all
array('foo', 'bar');Code: Select all
['foo'] is the first element and ['bar'] is the secondSimplified Recreation:
Code: Select all
private $_array;
private function _create($array)
{
$template = SomeClass::getTemplateString();
$this->_array = $array; // allows _parameterFormat access to the parameters; smelly
$ret = preg_replace_callback('/\$(\d+)/', array($this, '_parameterFormat'), $template);
$this->_array = null;
return $ret;
}
private function _parameterFormat($match)
{
return '[' . var_export($this->_array[$match[1]], true) . ']';
}