PHP preg_replace:使用变量
我在使用 preg_replace 中的变量时遇到问题。 基本上我想要实现的是在文本中寻找一些模式,并用内容替换它们。替换是在单独的函数(retrieveValue())中完成的。但是我在传递变量('$1')时遇到困难。
$types = array(
array(
'/\*#(.*?)#\*/',
$this->retrieveValue($templateVars,'$1')
)
);
foreach ($types as $type) {
$template = preg_replace($type[0], $type[1], $template);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是
$this->retrieveValue($templateVars,'$1')
是在调用preg_replace
之前执行的。解决方案:查看
preg_replace_callback
。我建议您在类中创建一个新方法:
然后可以使用:
您还可以使用 匿名函数。
The problem is that
$this->retrieveValue($templateVars,'$1')
is executed before you callpreg_replace
.Solution: Have a look at
preg_replace_callback
.I suggest you create a new method in your class:
and then can use:
You can also make use of anonymous functions in PHP 5.3.