PHP preg_replace: use variable(PHP PREG_REPLACE:使用变量)
问题描述
我在使用preg_place中的变量时遇到问题。 基本上,我想要实现的是在文本中寻找一些模式,并用内容取代它们。替换是在一个单独的函数中完成的,该函数是RetureValue()。但是,传递变量(‘$1’)时遇到困难。
$types = array(
array(
'/*#(.*?)#*/',
$this->retrieveValue($templateVars,'$1')
)
);
foreach ($types as $type) {
$template = preg_replace($type[0], $type[1], $template);
}
推荐答案
问题是$this->retrieveValue($templateVars,'$1')
在您调用preg_replace
之前执行。
解决方案:查看preg_replace_callback
。
我建议您在类中创建一个新方法:
public function _replace($matches) {
return $this->retrieveValue($templateVars, $matches[1]);
}
然后可以使用:
preg_replace_callback('/*#(.*?)#*/', array($this, '_replace'), $template);
您还可以在PHP 5.3中使用anonymous functions。
这篇关于PHP PREG_REPLACE:使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!