note 52274 added to function.convert-cyr-string

From: Date: Tue, 26 Apr 2005 20:38:14 +0000
Subject: note 52274 added to function.convert-cyr-string
Groups: php.notes 
Request: Send a blank email to php-notes+get-88590@lists.php.net to get a copy of this message
I needed a code for taking UTF8 encoded string from DB and printing it in Win1251 encoded HTML. The problem was that I had to print not just english & cyrillic characters, but all characters stored in UTF encoded string (in my case the DB contained english, russian & hebrew characters). After reading carefully the UTF8 manual, I've written the following code, that converts all non-win1251 characters into html entities (&#XXXX;). function utf8_2_win1251 ($str_src) { $str_dst = ""; $i = 0; while ($i<strlen($str_src)) { $code_dst = 0; $code_src1 = ord($str_src[$i]); $i++; if ($code_src1<=127) { $str_dst .= chr($code_src1); continue; } else if (($code_src1 & 0xE0) == 0xC0) { $code_src2 = ord($str_src[$i++]); if (($code_src2 & 0xC0) != 0x80) continue; $code_dst = ( ($code_src1 & 0x1F) << 6) + ($code_src2 & 0x3F); } else if (($code_src1 & 0xF0) == 0xE0) { $code_src2 = ord($str_src[$i++]); if (($code_src2 & 0xC0) != 0x80) continue; $code_src3 = ord($str_src[$i++]); if (($code_src3 & 0xC0) != 0x80) continue; $code_dst = ( ($code_src1 & 0x1F) << 12) + ( ($code_src2 & 0x3F) << 6) + ($code_src3 & 0x3F); } else if (($code_src1 & 0xF8) == 0xF0) { $code_src2 = ord($str_src[$i++]); if (($code_src2 & 0xC0) != 0x80) continue; $code_src3 = ord($str_src[$i++]); if (($code_src3 & 0xC0) != 0x80) continue; $code_src4 = ord($str_src[$i++]); if (($code_src4 & 0xC0) != 0x80) continue; $code_dst = ( ($code_src1 & 0x1F) << 18) + ( ($code_src2 & 0x3F) << 12) + ( ($code_src3 & 0x3F) << 6) + ($code_src4 & 0x3F); } else { continue; } if ($code_dst) { if ($code_dst==0x401) { $str_dst .= "¨"; } else if ($code_dst==0x451) { $str_dst .= "¸"; } else if ( ($code_dst>=0x410) && ($code_dst<=0x44F) ) { $str_dst .= chr ($code_dst-848); } else $str_dst .= "&#{$code_dst};"; } } return $str_dst; } ---- Manual Page -- http://www.php.net/manual/en/function.convert-cyr-string.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+52274 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+52274&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+52274&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+52274&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+52274&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+52274&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+52274&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#88590) next »