2011-10-20 23 views
0

我目前使用PHP的str_replace在循環中用另一個替換特定的值。PHP:如何順序替換字符串中的值?

問題是,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,但我與正則表達式平庸。

+1

類似,但絕對不重複......這一個希望限制只有一個替代總,我想要做的每個實例的順序替換針,具有不同的重置價值。 –

回答

4

未經測試,但我認爲這可以做到這一點。

$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

這隻會替代第一次出現,一次,永遠不會到第二次。 – rid

+0

+1。當我在這裏運行時工作:http://codepad.org/Sxpksp0A - 我想一個更有效的方法可能是使用一個調用preg_replace_callback()... –

+0

@Syntax錯誤,你是對的,抱歉,我誤解了這個問題。 – rid

-1

Apparantly這似乎工作:

$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

+0

謝謝,我沒有意識到str_replace的'count'特性!不幸的是,它似乎沒有做任何事情。我的結果沒有改變。此外,當我使用整數作爲數字而不是變量時,我得到了'致命錯誤:只有變量可以通過引用傳遞' –

+1

「count」參數是一個變量的引用,其中'str_replace()'將_write_替換次數。它與OP要求的內容無關。 – rid

+0

啊哈,這就解釋了爲什麼它似乎沒有做到我想的那樣,根據建議使用它! –

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); 
+0

是的,我只是注意到這個錯字,但是SE不允許我編輯它。在我的生產代碼中,該錯誤不存在。 –

+0

我站好了,編輯現在已經被批准。 –

+0

好的檢查一下我的編輯 – donutdan4114