Extra params for callback used with preg_replace_callback

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Extra params for callback used with preg_replace_callback

Post by Ollie Saunders »

I am creating a string using a template like this

Code: Select all

$0 is the first element and $1 is the second
and an array like this

Code: Select all

array('foo', 'bar');
into a result like this

Code: Select all

['foo'] is the first element and ['bar'] is the second
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:

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) . ']';
}
Solution doesn't necessary have to use preg_replace_callback() at all
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

Another approach (still using _callback) is to inject your array into the function source directly:

Code: Select all

private function _create($array)
{
    $template = SomeClass::getTemplateString();

    $ret = preg_replace_callback('/\$(\d+)/', create_function('$match', '
                                                       $array=' . var_export($array, true) .';
                                                       return $array[$match[1]];'), 
                                              $template);
    return $ret;
}
Alternatively, your could wrap the preg_replace_callback into the class, say, Replacer.
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

Thanks Weirdan, I think I'll live with it.
Post Reply