如何在 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()的返回分配给要使用的字符串,并使用带有分隔符和特殊语法的特定 A 模式进行正则表达式。 您还需要'b词边界,以防止替换redefineundelivered等中的red

$string = preg_replace("/'b$key'b/", $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;

使用上面的代码来获得预期的结果。

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

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