PHP preg_replace: use variable

2019-03-01 08:14发布

问题:

I'm having a problem using a variable from preg_replace. Basically what I want to achieve is to look for some patterns in a text, and replace them by content. The replacement is done in a seperate function (retrieveValue() ). However I'm having difficulties passing the variable ('$1').

$types = array(
        array(
                '/\*#(.*?)#\*/',
                $this->retrieveValue($templateVars,'$1')    
             )
        );

    foreach ($types as $type) {
        $template = preg_replace($type[0], $type[1], $template);
    }  

回答1:

The problem is that $this->retrieveValue($templateVars,'$1') is executed before you call preg_replace.

Solution: Have a look at preg_replace_callback.

I suggest you create a new method in your class:

public function _replace($matches) {
    return $this->retrieveValue($templateVars, $matches[1]);
}

and then can use:

preg_replace_callback('/\*#(.*?)#\*/', array($this, '_replace'), $template);

You can also make use of anonymous functions in PHP 5.3.