Search
Write a publication
Pull to refresh

Функции кодировки из UTF в WIN-1251 и обратно

Reading time5 min
Views897
<?php
function utf2win1251($content)
{
                $newcontent = "";

                for ($i = 0; $i < strlen($content); $i++)
                {
                        $c1 = substr($content, $i, 1);
                        $byte1 = ord($c1);
                        if ($byte1>>5 == 6)
                        {
                                $i++;
                                $c2 = substr($content, $i, 1);
                                $byte2 = ord($c2);
                                $byte1 &= 31;
                                $byte2 &= 63;
                                $byte2 |= (($byte1 & 3) << 6);
                                $byte1 >>= 2;
                                $word = ($byte1<<8) + $byte2;

                                if ($word == 1025) $newcontent .= chr(168);
                                else if ($word == 1105) $newcontent .= chr(184);
                                else if ($word >= 0x0410 && $word <= 0x044F) $newcontent .= chr($word-848);
                                else
                                {
                                        $a = dechex($byte1);
                                        $a = str_pad($a, 2, «0», STR_PAD_LEFT);
                                        $b = dechex($byte2);
                                        $b = str_pad($b, 2, «0», STR_PAD_LEFT);
                                        $newcontent .= "&#x".$a.$b.";";
                                }
                        }
                        else
                                $newcontent .= $c1;
                }

        return $newcontent;
}

function win12512utf($content)
{
                $content = preg_replace("#%u([0-9A-F]{1,4})#ie", "'&#'.hexdec('\\1').';'", $content);
                $content = html_entity_decode(urldecode($content), ENT_NOQUOTES, «windows-1251»);

        return $content;
}
?>
Tags:
Hubs:
Total votes 9: ↑1 and ↓8-7
Comments11

Articles