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

时间:2013-07-12 13:33:06

标签: php string replace preg-replace str-replace

尝试编写一个函数来纠正一组anacroyms的情况,但是无法看到如何更逻辑地做到这一点..

我现在有这个

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

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

有没有办法让一组字符串替换为一组替换?又名:

worda = Worda
wordb = woRdb

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

3 个答案:

答案 0 :(得分:1)

您可以将数组中的单词列表作为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); 

答案 1 :(得分:0)

嗯,看起来你不想多次写这个函数str_replace。 所以这是一个解决方案:

您可以将数据放在如下数组中:

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

希望这对你来说很容易。

然后使用foreach循环:

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

答案 2 :(得分:0)

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

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