开发者

PHP preg_replace: use variable

开发者 https://www.devze.com 2023-02-11 21:29 出处:网络
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 fu

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消