PHP文本到表情符号

PHP文本到表情符号,php,regex,preg-replace,Php,Regex,Preg Replace,我一直有点挣扎 关于这一点,我查了5个问题,但没有一个像我想象的那样有效。基本上我只是想用表情符号来代替“单词” 问题是我只想在这个词不是另一个词的一部分时转换这个词 这是我目前掌握的代码: $text = ":D i dont kn:ow about this :O i just want to :) and :D everyday:P"; $icons = array( ':)' => '<img class="postemot" src="/emoticons/

我一直有点挣扎

关于这一点,我查了5个问题,但没有一个像我想象的那样有效。基本上我只是想用表情符号来代替“单词”

问题是我只想在这个词不是另一个词的一部分时转换这个词

这是我目前掌握的代码:

$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;
$text=“:D我不知道:关于这个:O我只想:)和:D每天:P”;
$icons=数组(
':)' => '',
“:D'=>”,
':(' => '',
'>:O'=>'',
“:p'=>”,
“:P'=>”,
“:O'=>”,
“:o'=>”
);
foreach($图标为$图标=>$图像){
$icon=preg_quote($icon);
$text=preg_replace(“~\b$icon\b~”,$image,$text);
}
echo$文本;

但它就是不起作用。输出不正确。实际上,唯一输出的表情符号是最后一个,即“Daily:P”,这是不正确的。

在表情符号周围应用单词边界元字符是不正确的,因为

\b
匹配了不需要的位置:

everyday:P
        ^ asserts right before here
因此,您必须使用lookarounds处理另一个断言,以确保表情符号不被非空格字符包围:

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

(?你需要考虑的事情…表情符号什么时候是另一个单词的一部分?表情符号和单词的区别是什么?@Hallur-这不是区分它们的原因。这是让它们可以作为表情符号输出的原因。例如,当表情符号是单独的,周围没有其他字母时,让我们输出它。我不知道是什么老实说,你的意思是…$icon可以包含开始括号和结束括号;这些括号需要在regex中转义。@JosefScript请参见
preg\u quote
~(?请注意,这也可以在没有regex的情况下完成:
$text=str\u replace($icon“,$image“,$text”);