How to convert UTF-16 hex string to UTF-8 in PHP?

I have the following output from strace, and I want to convert it to UTF-8 using PHP:

R\00f6dhakev\00e4gen 4
R\00e4ntm\00e4starv\00e4gen 24
K\00d8BENHAVN

The above lines are UTF 16 HEX. I think so.

+3
source share
2 answers

Found that the following function works:

function utf8_urldecode($str) {

  $str = str_replace("\\00", "%u00", $str);

  $str = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($str));

  return html_entity_decode($str,null,'UTF-8');

}

Some parts from http://us2.php.net/manual/en/function.urldecode.php

+6
source

Try the following:

function masked_utf16_to_utf8($str) {
    $str = preg_replace_callback('/\\\\([0-9A-Fa-f]{2})([0-9A-Fa-f]{2})/', create_function('$match', 'return mb_convert_encoding(chr(hexdec("$match[1]")).chr(hexdec("$match[2]")), "UTF-8", "UTF-16");');
    return $str;
}
0
source

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


All Articles