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">
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"> .
This May Help...
Try to modify it as per your requirements...
$userComment = 'Hi this is a first comment i :heart: this comment :smile: .';
preg_match_all('/:(.*?)\:/s', $userComment, $m);
$newComment = str_replace($m[0], ' <img src="emoji/'.$m[1].'.png">', $userComment );
echo $newComment;