preg_replace /e 和数组
为什么这段代码不起作用?
$mx['foo'] = "vvv";
$string = "foo is foobar, baz is widgets";
echo preg_replace("/(foo)/ei", "$mx[('\\1')]", $string );
输出必须像这样
vvv 是 vvvbar,baz 是 widgets
why this code does not work ?
$mx['foo'] = "vvv";
$string = "foo is foobar, baz is widgets";
echo preg_replace("/(foo)/ei", "$mx[('\\1')]", $string );
the output must like this
vvv is vvvbar, baz is widgets
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
preg_replace
使用双引号,由 PHP 解释。看起来您不需要如此复杂的设置,因为据我所知,这是一个简单的字符串替换。一个更简单的解决方案是:您也可以使用数组:
这会将给定数组中的所有键替换为关联的值。
Your
preg_replace
uses double quotes, which are interpreted by PHP. It does not look like you need such a complex setup, since this is a simple string replacement, as far as i can see. A simpler solution would be:You could use your array, too:
This would replace all keys in the given array with the associated values.
因为您在
preg_replace
中使用双引号,PHP 会尝试直接使用您的$mx
值,这会产生错误...只需转义
$mx
code>,然后它就会起作用:或者您可以使用单引号执行相同的操作:
Because you are using double quotes in
preg_replace
, PHP tries to use your$mx
value directly, which produces then error...Simply escape the
$mx
, and then it will work:Or you can do the same by using single quotes: