How to convert Emoji from Unicode in PHP?

I use this table of Emoji and try this code:

<?php print json_decode('"\u2600"'); // This convert to ☀ (black sun with rays) ?>

If I try to convert this \u1F600 (grinning face) through json_decode, I see this symbol — ὠ0.

Whats wrong? How to get right Emoji?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

PHP 5

JSON’s \u can only handle one UTF-16 code unit at a time, so you need to write the surrogate pair instead. For U+1F600 this is \uD83D\uDE00, which works:

echo json_decode('"\uD83D\uDE00"');
😀

PHP 7

You now no longer need to use json_decode and can just use the \u and the unicode literal:

echo "\u{1F30F}";
🌏

Solution 2

In addition to the answer of Tino, I’d like to add code to convert hexadecimal code like 0x1F63C to a unicode symbol in PHP5 with splitting it to a surrogate pair:

function codeToSymbol($em) {
    if($em > 0x10000) {
        $first = (($em - 0x10000) >> 10) + 0xD800;
        $second = (($em - 0x10000) % 0x400) + 0xDC00;
        return json_decode('"' . sprintf("\\u%X\\u%X", $first, $second) . '"');
    } else {
        return json_decode('"' . sprintf("\\u%X", $em) . '"');
    }
}

echo codeToSymbol(0x1F63C); outputs 😼

Solution 3

May be somebody need example, parse string including emoji unicode format

$str = 'Test emoji \U0001F607 \U0001F63C';

echo preg_replace_callback(
    '/\\\U([A-F0-9]+)/',
    function ($matches) {
        return mb_convert_encoding(hex2bin($matches[1]), 'UTF-8', 'UTF-32');
    },
    $str
);

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply