PHP text for emoticons

I loved a little bit ...

I looked at about five questions about the stack thread, but none of them seemed to work the way I meant. Basically, I just want to replace the words β€œemoticons”.

The problem is that I want the word to be transformed only when the word is not part of another word.

This is the code that I still have:

$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 that just didn't work. The result was wrong. In fact, the last emoticon was the last one, "every day: P" , which is not true.

+5
source share
1 answer

The use of word boundary metacharacters around emoticons is incorrect, since \b corresponds to the desired position:

 everyday:P ^ asserts right before here 

Thus, you need to work with another statement using lookarounds to make sure the emoticon is not surrounded by a non-spatial character:

 (?<!\S)$icon(?!\S) 
+4
source

Source: https://habr.com/ru/post/1260608/


All Articles