i store codes "\u1f603" within messages in database, , need display corresponding emoji on web page.
how can convert \u1f603 \xf0\x9f\x98\x83 using php displaying emoji icons in web page?
you don't need convert emoji character codes utf-8 sequences, can use original 21-bit unicode value numeric character reference in html this: 😃
renders as: 😃.
the wikipedia article "unicode , html" explains:
in order work around limitations of legacy encodings, html designed such possible represent characters whole of unicode inside html document using numeric character reference: sequence of characters explicitly spell out unicode code point of character being represented. character reference takes form
&#
n;
, n either decimal number unicode code point, or hexadecimal number, in case must prefixedx
. characters compose numeric character reference universally representable in every encoding approved use on internet.for example, unicode code point u+5408, corresponds particular chinese character, has converted decimal number, preceded
&#
, followed;
, this:合
, produces this: 合.
so if in php code have string containing '\u1f603'
, can create corresponding html string using preg_replace, in following example:
$text = "this fun \\u1f603!"; // has 1 backslash, had escaped echo "database has: $text<br>"; $html = preg_replace("/\\\\u([0-9a-f]{2,5})/i", "&#x$1;", $text); echo "browser shows: $html<br>";
this outputs:
database has: fun \u1f603!
browser shows: fun 😃!
note if in data use literal \u
notation lower range unicode characters, i.e. hex numbers of 2 4 digits, must make sure next user's character not hex digit, lead wrong interpretation of \u
escape sequence stops. in case suggest left-pad these hex numbers zeroes in data 5 digits long.
to ensure browser uses correct character encoding, following:
- specify utf-8 character encoding in html
head
section:
<meta charset="utf-8">
- save php file in utf-8 encoding. depending on editor, may need use "save as" option, or find such setting in editor's "preferences" or "options" menu.
Comments
Post a Comment