Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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">
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
231 views
Welcome To Ask or Share your Answers For Others

1 Answer

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"> .

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...