2013-06-03 65 views
1

我對PHP很新,所以請耐心等待。PHP For Loop str_replace表情符號

我有一個表情符號的數組,我想用正確的圖像替換表情文本,所有這些都在for循環中。所以我正在嘗試使用我的文本變量並執行str_replace,但我不確定如何在表情符號更改後顯示文本。

這裏是我的代碼:

$content = ":D Here is a sample sentence for this example :)"; 

$emotes = array(
    [":)","<img class='emoticon' src='smile.png'>"], 
    [":D","<img class='emoticon' src='grin.png'>"], 
); 
for($i=0;$i<count($emotes);$i++) { 
    $contentWithEmotes = str_replace($emotes[$i][0], $emotes[$i][1], $content); 
} 
print $contentWithEmotes; 

的問題這是,它只能從陣列顯示最後一個圖像,當我希望它顯示他們兩個。 我應該如何着手顯示正確圖像的內容?

在此先感謝您的幫助。

+0

問題是,每一次通過循環,你都認爲原來的'$ content',而不是前面的替換結果。 – Barmar

回答

5

重塑你的數組是這樣的:

$emotes = [ 
    ":)"=>"<img class='emoticon' src='smile.png' />", 
    ":D"=>"<img class='emoticon' src=grin.png' />" 
]; 

然後使用strtr

$contentWithEmotes = strtr($content,$emotes); 
+0

啊,這是固定的。謝謝。 –

+0

+1 strtr <3我很喜歡這個。 – AlphaMale

0

通過你需要處理之前時間,而不是原來的內容,結果每一次循環中。

$contentWithEmotes = $content; 
foreach ($emotes as $emote) { 
    $contentWithEmotes = str_replace($emote[0], $emote[1], $contentWithEmotes); 
} 

但是,strtr()解決方案更好。