2013-06-03 2 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() 솔루션이 더 좋습니다.