问题
I have a chat box and would like to replace things such as ' :D ' with an icon.
$chatText = str_replace(":D","<img src='images/icons/smileys/smile-big.png' width='20' height='20' alt='Big Smile' />",$chatText);
Above is the code I'm using. On the chat, instead of replacing text with emotions, it literally replaces the ":D" with the html code:
<img src='images/icons/smileys/smile-big.png' width='20' height='20' alt='Big Smile' />
I have made a few attempts at changes (that I've researched) such as:
$chatText = str_replace(":D", "< img src=\"/images/icons/smileys/smile-big.png\" width=\"20\" height=\"20\" alt=\"Big Smile\" />",$chatText);
I've had no luck there. My question is how can I get this to work, so users are able to have emotions. At the very top of my code I also have $chatText = htmlspecialchars($chatText, ENT_QUOTES);
回答1:
I see a couple of possible problems — not 100% clear from your code:
Possibility #1: You're not setting the text in a TEXTAREA or something
If you're just setting the text for a textarea, then it doesn't support nested HTML, and you're not going to be able to do the smilies this way. Things like gmail and facebook, that DO support these, have basically re-implemented rendering of the content.
To correctly set the text, you want to use the innerHTML
property of some particular div
element to get the HTML correctly set.
In JQuery I'd probably write:
$('chat_text').html($('chat_text').html() + fixed_up_smilie_text);
Possibility #2: You're using htmlspecialchars
If you escape the text using htmlspecialchars
before putting it in the HTML, then you'll see what you're seeing above. The fix is easy: Don't ^_^.
来源:https://stackoverflow.com/questions/12161084/str-replace-text-with-image