str_replace-用另一组字符串替换一组字符串


str_replace - replace a set of strings with another set

试图编写一个函数来更正一组anacroyms的大小写,但看不到如何更合乎逻辑地执行。。

我现在有这个

$str = str_ireplace(" worda ", " Worda ", $str);
$str = str_ireplace(" wordb ", " woRrdb ", $str);

等等,这是一个很长的清单!

有没有办法让一组字符串替换为一组替换项?阿卡:

worda = Worda
wordb = woRdb

我也看到过其他使用preg_replace的例子,但也看不到使用该函数的方法。

您可以在str_ireplace、中给出数组中的单词列表作为参数

$str = str_ireplace(array("worda","wordb"),array("Worda","woRrdb"),$str); 

更漂亮,

$searchWords = array("worda","wordb");
$replaceWords = array("Worda","woRrdb");
$str = str_ireplace($searchWords,$replaceWords,$str); 

嗯,看起来您不想多次右写函数str_replace。因此,这里有一个解决方案:

你可以把你的数据放在一个数组中,比如:

$arr = array("worda" => "Worda", "wordb" => "woRdb");

希望这对你来说很容易。

然后使用foreach循环:

foreach($arr as $key => $value){
  $str = str_ireplace($key, $value, $str);
}

这里有一种使用关联数组的方法:

$words = array('worda' => 'Worda', 'wordb' => 'woRdb');
$str = str_ireplace(array_keys($words), array_values($words), $str);