2009-11-14 51 views
0

好吧,我有一個str_replace,我想做的是從數組中取值,並採取下一塊取代單詞「狗」。所以基本上我想要的$字符串爲:PHP str_replace與從循環陣列

「鴨子吃了貓和豬吃黑猩猩」

<?php 
$string = 'The dog ate the cat and the dog ate the chimp'; 
$array = array('duck','pig'); 
for($i=0;$i<count($array);$i++) { 
    $string = str_replace("dog",$array[$i],$string); 
} 
echo $string; 
?> 

此代碼只是返回:

「鴨子吃了貓鴨吃了黑猩猩「

我嘗試了幾件事情,但沒有任何工作。有人有主意嗎?

+0

我猜你可以使用'strstr'和'substr_replace'的組合。 – mpen 2009-11-14 06:09:33

回答

5

編輯:對不起,以前的錯誤答案。這將做到這一點。沒有str_replace,沒有preg_replace,只是原始,快速字符串搜索和拼接:

<?php 
$string = 'The dog ate the cat and the dog ate the chimp'; 
$array = array('duck', 'pig'); 
$count = count($array); 
$search = 'dog'; 
$searchlen = strlen($search); 
$newstring = ''; 
$offset = 0; 
for($i = 0; $i < $count; $i++) { 
    if (($pos = strpos($string, $search, $offset)) !== false){ 
     $newstring .= substr($string, $offset, $pos-$offset) . $array[$i]; 
     $offset = $pos + $searchlen; 
    } 
} 
$newstring .= substr($string, $offset); 
echo $newstring; 
?> 

附:在這個例子中沒有什麼大不了的,但你應該在你的循環之外保留count()。有了它,它就會在每次迭代中執行,並且比預先調用一次更慢。

+0

str_replace的第四個參數必須是一個變量,它將填充替換次數。不是你想要的。 – camomileCase 2009-11-14 05:57:55

+0

D'oh。通過文檔太快... – brianreavis 2009-11-14 05:59:21

+0

我用preg_replace替換了str_replace,因爲它使用了限制,現在我得到了「鴨子吃了貓,狗吃了黑猩猩」。它不會取代第二個「狗」= [ – David 2009-11-14 05:59:41

1

您的for循環$ string的第一次迭代之後,將用duck代替dog的兩次出現,以下迭代將不會執行任何操作。

我想不出解決這個更優雅的方式,我希望有更簡單的東西可能:

<?php 

$search = 'The dog ate the cat and the dog ate the chimp'; 
$replacements = array('duck','pig'); 
$matchCount = 0; 
$replace = 'dog'; 

while(false !== strpos($search, $replace)) 
{ 
    $replacement = $replacements[$matchCount % count($replacements)]; 
    $search = preg_replace('/('.$replace.')/', $replacement, $search, 1); 
    $matchCount++; 
} 

echo $search; 
+0

哇嘿,至少它的作品,我今晚會過去,所以我完全理解它。 =]非常感謝! – David 2009-11-14 06:01:55

2
<?php 
$string = 'The dog ate the cat and the dog ate the chimp'; 
$array = array('duck', 'pig'); 

$count = count($array); 

for($i = 0; $i < $count; $i++) { 
    $string = preg_replace('/dog/', $array[$i], $string, 1); 
} 

echo $string; 
?> 

鴨子吃了貓和豬吃黑猩猩

+0

哦,我想我明白了,如果你在所有的陳述中保留了相同的變量「$ string」,我會假設它會起作用嗎? – David 2009-11-14 06:29:33

+0

它會工作。第一圈$ str =鴨子吃了貓,狗吃了黑猩猩。第二圈鴨子吃了貓,豬吃了黑猩猩。 – lemon 2009-11-14 07:30:31

0

又一個選項

$str = 'The dog ate the cat and the dog ate the chimp'; 
$rep = array('duck','pig'); 
echo preg_replace('/dog/e', 'array_shift($rep)', $str); 
0

使用substr_replace();

<?php 
function str_replace_once($needle, $replace, $subject) 
{ 
    $pos = strpos($subject, $needle); 
    if ($pos !== false) 
     $subject = substr_replace($subject, $replace, $pos, strlen($needle)); 
    return $subject; 
} 

$subject = 'The dog ate the cat and the dog ate the chimp'; 
$subject = str_replace_once('dog', 'duck', $subject); 
$subject = str_replace_once('dog', 'pig', $subject); 

echo $subject; 
?>