PHP Preg Replace 替换数组
好吧,我正在尝试这样做:
preg_replace("/\{([a-zA-Z0-9_]+)\}/", $templateVariables[$1], $templateString);
现在我知道这是不可能的,但是我想知道是否有办法做到这一点,因为我尝试使用 create_function 但是, $templateVariables 是函数的局部变量,它是内,所以我无法从 create_function 内访问 $templateVariables,所以我有点卡在这里。我宁愿不必找到匹配项找出用什么来替换它们,然后再次找到它们来替换,这看起来效率很低。那么,我是否可以从匿名函数中获取局部变量,或者有人有什么好的建议吗?
谢谢。
Ok so I'm trying to do something like so:
preg_replace("/\{([a-zA-Z0-9_]+)\}/", $templateVariables[$1], $templateString);
Now I know that is not possible like it is, however I would like to know if there is a way to do this, because I have tried to use create_function however, $templateVariables is a local variable to the function that it is within, so I can't access $templateVariables from within create_function, so I'm kind of stuck here. I would rather not have to find the matches figure out what to replace them with and then find them again to replace, that just seems horrible inefficient. So is there anyway I can get to a local variable from within an anonymous function or does anyone have any good suggestions.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
它应该输出:
您可以在此处查看一个工作示例 http://codepad.viper-7.com/2ZNNYZ< /a>
Try this:
It should output:
You can see a working example here http://codepad.viper-7.com/2ZNNYZ
您实际上可以将 preg_replace 与 /e 修饰符一起使用:
但这可能不是最安全的方法......
You can actually use preg_replace with /e modifier:
But it may not be the safest way here...
您需要使用 e 正则表达式修饰符:
You need to use e regexp modifier: