如果键在文本中,则替换 [英] Replace if key is in a text
问题描述
我正在尝试使用 php 为我的网站评论区域制作表情符号系统.我已经为表情符号列表创建了表格.像这样:
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:
这是我的第一条评论 :heart:
这条评论 :smile:
.
Hi this is a first comment i :heart:
this comment :smile:
.
我想检测表情符号的文本.如果注释中存在 emoji_key,则将 :heart: 替换为 heart.png .
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 ?
例如:
$userComment = '这是第一条评论我 :heart: 这个评论 :smile: .';
普林应该是这样的:
Hi this is my first comment <img src="emoji/heart.png"> this comment <img src="emoji/smile.png">
推荐答案
我假设您正在使用 mysqli 并且您的连接名为 $conn
.首先,您需要在用户评论中找到表情符号字符串,您可以使用 preg_match_all
:
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);
现在你可以在你的表情符号表中搜索这些字符串(我假设它叫做emojis
:
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);
现在检查结果并使用 str_replace
:
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;
输出:
Hi this is a first comment i <img src="emoji/heart.png"> this comment <img src="emoji/smile.png"> .
这篇关于如果键在文本中,则替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!