1

试图编写一个函数来纠正一组字谜的大小写,但看不出如何更合乎逻辑地做到这一点..

我现在有这个

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

等等,它的清单很长!

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

worda = Worda
wordb = woRdb

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

4

3 回答 3

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); 
于 2013-07-12T13:39:24.710 回答
0

嗯,看起来您不想str_replace多次正确编写该函数。所以这里有一个解决方案:

您可以将数据放入数组中,例如:

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

希望这对您来说很容易。

然后使用foreach循环:

foreach($arr as $key => $value){
  $str = str_ireplace($key, $value, $str);
}
于 2013-07-12T13:40:37.803 回答
0

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

$words = array('worda' => 'Worda', 'wordb' => 'woRdb');
$str = str_ireplace(array_keys($words), array_values($words), $str);
于 2013-07-12T13:42:46.497 回答