Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

php - Replace if key is in a text

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...