Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP text to emoticons

Tags:

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.

like image 476
Steven Dropper Avatar asked Nov 30 '16 20:11

Steven Dropper


1 Answers

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

everyday:P
        ^ 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:

(?<!\S)$icon(?!\S)
like image 98
revo Avatar answered Sep 25 '22 17:09

revo