PHP preg_replace: use variable

前端 未结 1 1050
天命终不由人
天命终不由人 2021-01-24 19:53

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 i

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-24 20:12

    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 讨论(0)
提交回复
热议问题