PHP文本到表情符号

Ste*_*per 5 php regex preg-replace

我有点挣扎......

我查看了5个关于此问题的stackoverflow问题,但它们似乎都没有像我想象的那样工作.基本上我只是想用表情符号替换"单词".

问题是我希望只有在单词不是另一个单词的一部分时才能转换单词.

这是我到目前为止的代码:

$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;
Run Code Online (Sandbox Code Playgroud)

但它只是没有用.输出不正确.实际上唯一输出的表情是最后一个,"每天:P",这是不正确的.

rev*_*evo 4

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

everyday:P
        ^ asserts right before here
Run Code Online (Sandbox Code Playgroud)

因此,您必须使用环视来处理另一个断言,以确保表情符号不被非空格字符包围:

(?<!\S)$icon(?!\S)
Run Code Online (Sandbox Code Playgroud)