PHP Function to Convert from Unicode to any Charset

By | January 28, 2010

When you are dealing with encoded strings it is not so easy to determine the encoding. But if your string is converted to unicode, there are no standard PHP functions to decode it. I have found a function that allows to convert a unicode string to any charset you like. Here it is:

<? function Unicode2Charset($str, $charset = ‘Windows-1251’) { // by SiMM, addition by John Profic return preg_replace( ‘~&#(?:x([da-f]+)|(d+));~ie’, ‘iconv(“UTF-16LE”, $charset, pack(“v”, “$1” ? hexdec(“$1”) : “$2”))’, $str ); } ?>

I have posted a Windows-1251 example, but you are welcome to convert to any other encoding you need.