如何使用 php 中的数组替换字符串中的单词?

How can i replace words in a string using an array in php?

我正在尝试搜索一个字符串,并在每次出现第一个字符串时将某个字符串的所有实例替换为另一个字符串。

我的目标是避免使用许多 preg-replace 语句并制作一个易于编辑和维护的数组,其中包含与我要替换的单词相同的键和包含替换的值。

到目前为止我有这样的东西:

$colors = array('red' => 'i am the color red', 'blue' => 'hi I am       blue',);

$string = "red, blue, red, and lots of blue";
foreach($colors as $key => $value) {
    preg_replace($key, $value, $string);
    echo $string;
}

这还没有用。

你正在做直接字符串替换(没有正则表达式)所以使用:

$string = str_replace(array_keys($colors), $colors, $string);

无需循环,str_replace() 采用数组。

仅供参考:在您的代码中,除了解析错误之外,您没有将 preg_replace() 的 return 分配回要使用的字符串,也没有使用特定模式的正则表达式定界符和特殊语法。您还需要单词边界 \b 以防止替换 redefineundelivered 等中的 red

$string = preg_replace("/\b$key\b/", $value, $string);

http://php.net/manual/en/function.str-replace.php

echo str-replace($key, $value, $string);

$colors = array('red' => 'i am the color red', 'blue' => 'hi Im blue');
$string = "red, blue, red, and lots of blue";
foreach($colors as $key => $value) {
    $string = str_replace($key, $value, $string);
}
echo $string;

使用上面的代码得到你预期的结果。