【问题标题】:str_replace - replace a set of strings with another setstr_replace - 用另一组字符串替换一组字符串
【发布时间】:2013-07-11 01:39:48
【问题描述】:

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

我现在有这个

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

等等,一长串!

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

worda = Worda
wordb = woRdb

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

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

      希望这对你来说很容易。

      然后使用foreach 循环:

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-05-14
          • 2013-12-03
          • 2017-01-28
          • 2017-03-07
          • 1970-01-01
          相关资源
          最近更新 更多