How to create javascript escape sequences in PHP?

I am looking for a way to create valid UTF-16 JavaScript escape characters (including surrogate pairs) from PHP.

I use the code below to get UTF-32 code points (from a UTF-8 encoded character). This works like JavaScript escape characters (for example, "\ u00E1" for "รก") - until you get to the upper ranges where you get surrogate pairs (for example, "๐œ•" goes like "\ u1D715", but should be " \ uD835 \ uDF15 ') ...

function toOrdinal($chr) { if (ord($chr{0}) >= 0 && ord($chr{0}) <= 127) { return ord($chr{0}); } elseif (ord($chr{0}) >= 192 && ord($chr{0}) <= 223) { return (ord($chr{0}) - 192) * 64 + (ord($chr{1}) - 128); } elseif (ord($chr{0}) >= 224 && ord($chr{0}) <= 239) { return (ord($chr{0}) - 224) * 4096 + (ord($chr{1}) - 128) * 64 + (ord($chr{2}) - 128); } elseif (ord($chr{0}) >= 240 && ord($chr{0}) <= 247) { return (ord($chr{0}) - 240) * 262144 + (ord($chr{1}) - 128) * 4096 + (ord($chr{2}) - 128) * 64 + (ord($chr{3}) - 128); } elseif (ord($chr{0}) >= 248 && ord($chr{0}) <= 251) { return (ord($chr{0}) - 248) * 16777216 + (ord($chr{1}) - 128) * 262144 + (ord($chr{2}) - 128) * 4096 + (ord($chr{3}) - 128) * 64 + (ord($chr{4}) - 128); } elseif (ord($chr{0}) >= 252 && ord($chr{0}) <= 253) { return (ord($chr{0}) - 252) * 1073741824 + (ord($chr{1}) - 128) * 16777216 + (ord($chr{2}) - 128) * 262144 + (ord($chr{3}) - 128) * 4096 + (ord($chr{4}) - 128) * 64 + (ord($chr{5}) - 128); } } 

How do I configure this code to give me the correct UTF-16 code points? Thanks!

+4
source share
2 answers

How to use iconv (or similarly mb_convert_encoding )?

eg. sort of:

 $utf16= iconv('UTF-8', 'UTF-16LE', $text); $codeunits= array(); for ($i= 0; $i<strlen($utf16); $i+= 2) { $codeunits[]= ord($utf16{$i})+ord($utf16{$i+1})<<8; } 
+1
source

Here's the last code used (based on a response from bobince):

 $output = ''; $utf16 = iconv(fxCHARSET, 'UTF-16BE', $text); for ($i= 0; $i < strlen($utf16); $i+= 2) { $output.= '\\u'.str_pad(dechex((ord($character{$i}) << 8) + ord($character{$i+1})), 4, '0', STR_PAD_LEFT); } 
0
source

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


All Articles