2011年9月9日 星期五

php utf8 2 unicode,unicode 2 utf8

<?  
// utf8 - unicode  
function utf8_unicode($c) {  
   switch(strlen($c)) {  
     case 1:  
       return ord($c);  
     case 2:  
       $n = (ord($c[0]) & 0x3f) << 6;  
       $n += ord($c[1]) & 0x3f;  
       return $n;  
     case 3:  
       $n = (ord($c[0]) & 0x1f) << 12;  
       $n += (ord($c[1]) & 0x3f) << 6;  
       $n += ord($c[2]) & 0x3f;  
       return $n;  
     case 4:  
       $n = (ord($c[0]) & 0x0f) << 18;  
       $n += (ord($c[1]) & 0x3f) << 12;  
       $n += (ord($c[2]) & 0x3f) << 6;  
       $n += ord($c[3]) & 0x3f;  
       return $n;  
   }  
}  
function u2utf8($c) {    
    $str="";    
    if ($c < 0x80) $str.=$c;    
    else if ($c < 0x800) {    
        $str.=chr(0xC0 | $c>>6);    
        $str.=chr(0x80 | $c & 0x3F);    
    } else if ($c < 0x10000) {    
        $str.=chr(0xE0 | $c>>12);    
        $str.=chr(0x80 | $c>>6 & 0x3F);    
        $str.=chr(0x80 | $c & 0x3F);    
    } else if ($c < 0x200000) {    
        $str.=chr(0xF0 | $c>>18);    
        $str.=chr(0x80 | $c>>12 & 0x3F);    
        $str.=chr(0x80 | $c>>6 & 0x3F);    
        $str.=chr(0x80 | $c & 0x3F);    
    }  
    return $str;    
}  
  
echo u2utf8('20197');  
echo utf8_unicode('電');  
?>

沒有留言:

張貼留言