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条)

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法