PHP preg_replace - 使用匹配作为键从数组中查找替换
我有一个字符串,它可以包含多个匹配项(百分号包围的任何单词)和一个替换数组 - 每个替换的关键是正则表达式的匹配。一些代码可能会更好地解释这一点......
$str = "PHP %foo% my %bar% in!";
$rep = array(
'foo' => 'does',
'bar' => 'head'
);
期望的结果是:
$str = "PHP does my head in!"
我已经尝试了以下方法,但没有一个起作用:
$res = preg_replace('/\%([a-z_]+)\%/', $rep[$1], $str);
$res = preg_replace('/\%([a-z_]+)\%/', $rep['$1'], $str);
$res = preg_replace('/\%([a-z_]+)\%/', $rep[\1], $str);
$res = preg_replace('/\%([a-z_]+)\%/', $rep['\1'], $str);
因此我向 Stack Overflow 寻求帮助。有接受者吗?
I have a string which can contain multiple matches (any word surrounded by percentage marks) and an array of replacements - they key of each replacement being the match of the regex. Some code will probably explain that better...
$str = "PHP %foo% my %bar% in!";
$rep = array(
'foo' => 'does',
'bar' => 'head'
);
The desired result being:
$str = "PHP does my head in!"
I have tried the following, none of which work:
$res = preg_replace('/\%([a-z_]+)\%/', $rep[$1], $str);
$res = preg_replace('/\%([a-z_]+)\%/', $rep['$1'], $str);
$res = preg_replace('/\%([a-z_]+)\%/', $rep[\1], $str);
$res = preg_replace('/\%([a-z_]+)\%/', $rep['\1'], $str);
Thus I turn to Stack Overflow for help. Any takers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
给出:
请参阅修饰符“e”的文档。
gives:
See the docs for the modifier 'e'.
似乎修饰符“e”已被弃用。存在安全问题。
或者,您可以使用 preg_replace_callback。
It seems that the modifier "e" is deprecated. There are security issues.
Alternatively, you can use the preg_replace_callback.
您可以使用 eval 修饰符...
You could use the eval modifier...
只是为了提供 preg_replace() 的替代方案:
Just to provide an alternative to preg_replace():