douqi2804 2018-11-27 10:38
浏览 31
已采纳

如果密钥在文本中,则替换

I am trying to make a emoji system using php for my website comment earea. I have created the table for emoji list. Like this:

+----------+------------+-------------+
| emoji_id |  emoji_key |  emoji_img  |
+----------+------------+-------------+
|    1     |   :smile:  |  smile.png  |
+----------+------------+-------------+
|    2     |   :heart:  |  heart.png  |
+----------+------------+-------------+

So for example user posted a comment like this:

Hi this is a first comment i :heart: this comment :smile: .

I want to detect the text for emoji. If emoji_key is exist in the comment then replace the :heart: to heart.png .

<img src="emoji/<?php echo $emoji_img;?>" />

is there anyway to do this ?

For example:

$userComment = 'Hi this is a first comment i :heart: this comment :smile: .'; Pring should like this:

Hi this is my first comment <img src="emoji/heart.png"> this comment <img src="emoji/smile.png">
  • 写回答

2条回答 默认 最新

  • dongyi3776 2018-11-27 11:15
    关注

    I'm assuming that you're using mysqli and your connection is called $conn. First, you need to find the emoji strings in your user comment, which you can do with preg_match_all:

    preg_match_all('/(:\w+:)/', $userComment, $matches);
    

    Now you can search for those strings in your emoji table (I'm assuming it's called emojis:

    $sql = "SELECT * FROM emojis WHERE emoji_key IN ('" . implode("','", $matches[1]) . "')";
    $result = $conn->query($sql);
    

    Now go through the results and replace the values in your string using str_replace:

    while ($row = $result->fetch_assoc()) {
        $userComment = str_replace($row['emoji_key'], "<img src=\"emoji/{$row['emoji_img']}\">", $userComment);
    }
    echo $userComment;
    

    Output:

    Hi this is a first comment i <img src="emoji/heart.png"> this comment <img src="emoji/smile.png"> .
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理