PHP:如何按顺序替换字符串中的值?

时间:2011-10-20 01:07:26

标签: php string

我目前正在使用PHP的str_replace在循环中用另一个替换特定值。

问题是,str_replace将用第二个值替换第一个值的所有实例,而不是按顺序替换它们。例如:

$replacements = array('A', 'one', 'some');
$str = "The quick brown fox jumps over the lazy dog and runs to the forest.";
foreach($replacements as $replace){
    $str = str_replace('the', $replace, $str);
}

这将最终回归:

“快速的棕色狐狸跳过一只懒狗跑到森林里。”

而不是我想要的那样:

“快速的棕色狐狸跳过一只懒狗跑到一片森林里。”

这样做最有效的方法是什么?我以为我可以使用preg_replace,但我对正则表达式很平庸。

3 个答案:

答案 0 :(得分:5)

未经测试,但我认为这样可以解决问题。

$replacements = array('A', 'one', 'some');
$str = "The quick brown fox jumps over the lazy dog and runs to the forest.";
foreach($replacements as $replace){
    $str = preg_replace('/the/i', $replace, $str, 1);
}
echo $str;

编辑:添加了i以使其不区分大小写

答案 1 :(得分:0)

好吧,这可能是超级错综复杂的?

$replacements = array('A', 'one', 'some');
$str = "The quick brown fox jumps over the lazy dog and runs to the forest.";
$str_array = explode(" ", $str);
$replace_word = "the";
$i = $j = 0;
foreach($str_array as $word){
      if(strtolower($word) === $replace_word){
         $str_array[$i] = $new_word[$j];
         $j++;
      }
   $i++;
}
$str = implode(" ", $str_array);

答案 2 :(得分:-1)

显然这似乎有效:

$replacements = array('A', 'one', 'some');
$the=array('the','the','the');
$str = "The quick brown fox jumps over the lazy dog and runs to the forest.";
$str = str_ireplace($the, $replacements, $str);

我认为这正是被问到的。

请参阅参数说明http://php.net/manual/en/function.str-replace.php

http://codepad.org/VIacFmoM