preg_replace /e 和数组

发布于 2024-09-18 01:33:26 字数 219 浏览 4 评论 0原文

为什么这段代码不起作用?

$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

日记撕了你也走了 2024-09-25 01:33:31

您的 preg_replace 使用双引号,由 PHP 解释。看起来您不需要如此复杂的设置,因为据我所知,这是一个简单的字符串替换。一个更简单的解决方案是:

$string = str_replace('foo', 'vvv', $string);

您也可以使用数组:

$replacements = array(
    'foo' => 'vvv'
);
foreach ($replacements as $key => $replacement) {
    $string = str_replace($key, $replacement, $string);
}

这会将给定数组中的所有键替换为关联的值。

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:

$string = str_replace('foo', 'vvv', $string);

You could use your array, too:

$replacements = array(
    'foo' => 'vvv'
);
foreach ($replacements as $key => $replacement) {
    $string = str_replace($key, $replacement, $string);
}

This would replace all keys in the given array with the associated values.

美人骨 2024-09-25 01:33:29

因为您在 preg_replace 中使用双引号,PHP 会尝试直接使用您的 $mx 值,这会产生错误...

只需转义 $mx code>,然后它就会起作用:

echo preg_replace("/(foo)/ei",  "\$mx[('\\1')]",  $string );

或者您可以使用单引号执行相同的操作:

echo preg_replace("/(foo)/ei",  '$mx[(\'\\1\')]',  $string );

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:

echo preg_replace("/(foo)/ei",  "\$mx[('\\1')]",  $string );

Or you can do the same by using single quotes:

echo preg_replace("/(foo)/ei",  '$mx[(\'\\1\')]',  $string );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文