posts - 6, comments - 6, trackbacks - 0, articles - 0

一个将utf-8转为gb2312的简单程序

Posted on 2007-04-16 19:38 吴涛涛 阅读(1614) 评论(0)  编辑  收藏
<?
//utf-8->gb2312函数,本程序没有用到,仅供参考
function u2utf82gb($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 iconv('UTF-8', 'GB2312', $str);
}
function unescape($str) {
$str = rawurldecode($str);
preg_match_all("/(?:%u.{4})|.{4};|&#\d+;|.+/U",$str,$r);
$ar = $r[0];
print_r($ar);
foreach($ar as $k=>$v) {
  if(substr($v,0,2) == "%u")
    $ar[$k] = iconv("UCS-2","GB2312",pack("H4",substr($v,-4)));
  elseif(substr($v,0,3) == "")
    $ar[$k] = iconv("UCS-2","GB2312",pack("H4",substr($v,3,-1)));
  elseif(substr($v,0,2) == "&#") {
echo substr($v,2,-1)."<br>";
    $ar[$k] = iconv("UCS-2","GB2312",pack("n",substr($v,2,-1)));
  }
}
return join(" ",$ar);
}
//下面是转换功能
$db = mysql_connect("localhost", "dbname", "password");
mysql_select_db("dbname",$db);
$result = mysql_query("SELECT * FROM dede_archives",$db);
if ($result === false) die("failed");
while ($fields = mysql_fetch_row($result)) {
        $con=$fields[10];
        $con = iconv("UTF-8","GB2312",$con);//主要是iconv函数的使用
        $update="update dede_archives set title='".$con."' where ID=".$fields[0];
        //echo $update;
        mysql_query($update);
        echo $fields[0]."OK"."<br />";
}
?>

只有注册用户登录后才能发表评论。


网站导航: