Steven Dropper Steven Dropper - 10 months ago 85
PHP Question

PHP text to emoticons

I've been kinda struggling a little...

I looked up around 5 stackoverflow questions about this, but none of them seemed to work the way I have in mind. Basically I just want to replace "words" with emoticons.

The problem is that I want the word to be converted only when the word isn't a part of another word.

This is the code I have so far:

$text = ":D i dont kn:ow about this :O i just want to :) and :D everyday:P";
$icons = array(
':)' => '<img class="postemot" src="/emoticons/smile_yell.png" />',
':D' => '<img class="postemot" src="/emoticons/laugh_yell.png" />',
':(' => '<img class="postemot" src="/emoticons/sad_yell.png" />',
'>:O' => '<img class="postemot" src="/emoticons/scared_yell.png" />',
':p' => '<img class="postemot" src="/emoticons/tongue_yell.png" />',
':P' => '<img class="postemot" src="/emoticons/tongue_yell.png" />',
':O' => '<img class="postemot" src="/emoticons/surprised_yell.png" />',
':o' => '<img class="postemot" src="/emoticons/surprised_yell.png" />'
foreach($icons as $icon=>$image) {
$icon = preg_quote($icon);
$text = preg_replace("~\b$icon\b~",$image,$text);
echo $text;

But it just didn't work. The output was not correct. Actually the only outputted emoticon was the last one, the "everyday:P", which is incorrect.

Answer Source

Applying word boundary metacharacters around emoticons is not right since \b matches a position that is not desired:

        ^ asserts right before here

So you have to work with another assertion using lookarounds to ensure emoticon is not surrounded by a non-space character: