[英]PHP For Loop str_replace emoticons
I'm pretty new to PHP so please bear with me for this one. 我对PHP来说还很陌生,所以请耐心等待。
I have an array with emoticons, and I want to replace the emoticon text with the correct image, all within a for loop. 我有一个带有表情符号的数组,我想用正确的图像替换表情符号文本,所有这些都在for循环内。 So I'm trying to take my text variable and do a str_replace, but I'm not sure exactly how to display the text after the emoticons have been changed. 因此,我尝试获取文本变量并执行str_replace,但是我不确定在表情符号更改后如何确切显示文本。
Here is my code: 这是我的代码:
$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;
The problem this this is that it only displays the last image from the array, when I want it to display both of them. 这个问题是,当我希望它显示两个图像时,它仅显示数组中的最后一个图像。 How should I go about displaying the content with the correct image? 如何显示具有正确图像的内容?
Thanks in advance for any help. 在此先感谢您的帮助。
Each time through the loop you need to process the result of the previous time, not the original content. 每次循环时,您都需要处理上一次的结果,而不是原始内容。
$contentWithEmotes = $content;
foreach ($emotes as $emote) {
$contentWithEmotes = str_replace($emote[0], $emote[1], $contentWithEmotes);
}
However, the strtr()
solution is better. 但是, strtr()
解决方案更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.