In daily life, the user sends the content that contains the emoji expression, untreated, in the display is garbled. So this article introduces several processing methods of emoji expression involved in PHP development. We hope to help you.
Background
When you do development, you will find that storing nicknames is essential.
But this evil support emoji expression do nickname, it is a bit of egg pain
The General MySQL table is designed with the UTF8 character set. The nickname field with emoji is gone insert
, and the entire field becomes an empty string. What's going on here?
It turns out that MySQL's UTF8 character set is 3 bytes, and emoji is 4 bytes, so the entire nickname cannot be stored. What's going to happen? Let me introduce several methods.
Solution Solutions
1. Using the UTF8MB4 character set
If your MySQL version >=5.5.3
, you can directly utf8
upgrade directly to the utf8mb4
character set
This 4-byte UTF8 encoding is perfectly compatible with the old 3-byte UTF8 character set and can store emoji emoticons directly, which is the best solution
As for the performance loss caused by the increase in bytes, I've seen some reviews that are almost negligible
2. Using Base64 encoding
If you can't use UTF8MB4 for some reason, you can also use the base64
curve to salvation
Using functions such as base64_encode
the emoji can be stored directly in the UTF8 byte set of the data table, when taken out decode a bit
3, kill emoji expression
Emoji expression is a troublesome thing, and even if you can store it, it doesn't have to be perfectly displayed. On a platform other than iOS, such as a PC or Android. If you need to display emoji, you have to prepare a bunch of emoji images and use a third-party front-end class library. Even so, it may be because emoji pictures are not enough to show the situation in most business scenarios, emoji is not a must. We can think of it properly and save a variety of costs.
After a hard Google, finally found a reliable code:
Filter out emoji expression function Filteremoji ($str) {$str = Preg_replace_callback ( '/./u ', function (array $match) { return strlen ($match [0]) >= 4? ": $match [0]; }, $str); return $str; }
Related recommendations:
How PHP generates MySQL data dictionary
PHP implementation of Word statistics function
How PHP handles binary data