PHP 文字转表情

PHP text to emoticons

我有点挣扎...

我查了大约 5 个与此相关的 Whosebug 问题,但其中 none 似乎符合我的想法。基本上我只是想用表情符号替换 "words" 。

问题是我希望仅当该词不属于另一个词时 才转换该词。

这是我目前的代码:

$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;

但就是没用。输出不正确。实际上只输出了最后一个"everyday:P",这是不正确的

在表情符号周围应用单词边界元字符是不正确的,因为 \b 匹配了不需要的位置:

everyday:P
        ^ asserts right before here

所以你必须使用环视来处理另一个断言,以确保表情符号不被非space字符包围:

(?<!\S)$icon(?!\S)