Encode emoji to Unicode code point - PHP / JS

Say I have this line in PHP:

$str = '🀄️';

Or this line in JavaScript:

var str = '🀄️';

If I do utf8_encode($str), the result is equal \ud83c\udc04\ufe0f, but I want it to be 1F004either 1F004or \u1f004to search for an image file matching this symbol.

I have done a lot of multi-user searches that are looking for a way to encode it. I found that there are many places where the same terms are used for a variety of things, it looks like I want to “encode” a string to a UTF-32 code point, but I really don't know what to name what I I want, I just want to convert this 🀄️to this 1F004using PHP and / or JavaScript.

http://www.fileformat.info/info/unicode/char/1f004/index.htm

Thanks.

+4
2

, utf8_encode . .

function utf8_to_unicode($c)
{
    $ord0 = ord($c{0}); if ($ord0>=0   && $ord0<=127) return $ord0;
    $ord1 = ord($c{1}); if ($ord0>=192 && $ord0<=223) return ($ord0-192)*64 + ($ord1-128);
    $ord2 = ord($c{2}); if ($ord0>=224 && $ord0<=239) return ($ord0-224)*4096 + ($ord1-128)*64 + ($ord2-128);
    $ord3 = ord($c{3}); if ($ord0>=240 && $ord0<=247) return ($ord0-240)*262144 + ($ord1-128)*4096 + ($ord2-128)*64 + ($ord3-128);
    return false;
}

var_dump( dechex(utf8_to_unicode('🀄️')) ); // string(5) "1f004"

UTF-8 ASCII, $ord0 = ord($c{0}); if ($ord0>=0 && $ord0<=127) return $ord0; . 127 . 1920 , $ord1 = ord($c{1}); if ($ord0>=192 && $ord0<=223) return ($ord0-192)*64 + ($ord1-128);. 192 (11000000) 223 (11011111), . 10xxxxxx ( 128 191 ). U + 0080, U + 07FF.

.

+2

JavaScript:

function e2u(str){
    str = str.replace(/\ufe0f|\u200d/gm, ''); // strips unicode variation selector and zero-width joiner
    var i = 0, c = 0, p = 0, r = [];
    while (i < str.length){
        c = str.charCodeAt(i++);
        if (p){
            r.push((65536+(p-55296<<10)+(c-56320)).toString(16));
            p = 0;
        } else if (55296 <= c && c <= 56319){
            p = c;
        } else {
            r.push(c.toString(16));
        }
    }
    return r.join('-');
}
+4

Source: https://habr.com/ru/post/1607571/


All Articles