表情符号的preg_replace(php)


preg_replace for emoticons (php)

根据旧问题修订-现在使用不同的前进方向

我正在建立一个聊天框,并希望使用表情符号。因此,当一个人发送":)"时,它会被它的图像所取代,不幸的是,在我的代码中,这并没有发生。我也做了很多实验,我知道str_replace会实现我的项目鹅蛋,我决定使用preg_replace

<?php
$message = $chatText;
$emoticons = array(
"/':')/");

$replacements = array(
"<img src='images/icons/smileys/smile.png' width='20' height='20' alt='Smile' />");

$chatText = preg_replace($emoticons,$replacements,$message);

?>

它没有将":)"替换为笑脸,而是插入文本<img src='images/icons/smileys/smile.png' width='20' height='20' alt='Smile' />

这不是正则表达式的问题,而是如何显示数据的问题。在某种程度上,您正在使用类似htmlspecialchars的东西来防止聊天者将HTML注入您的聊天窗口。不幸的是,这也导致了笑脸被转义。

替换smileys的代码应该位于转义原始文本后的处。