daresheep

重点关注web2.0/asp.net/php/ajax

[导入]关于Google和百度对中文URI编码不同的解决方案


百度跟谷歌在 对页面收集的时候.百度对含有中文的URI的编码是通过GB2312来编码的,至于它是不是根据页面编码来的,没有去深入研究,但是谷歌确是用UTF-8编码的,这样,造成了很严重的问题,用中文地址传递参数在被谷歌收录后是不能被正确识别的

所以.我写了一个函数,核心代码是参考的 php手册上关于mb_detect_encoding的有关解释写的..
具体内容如下:

//
//    utf8 encoding validation developed based on Wikipedia entry at:
//    http://en.wikipedia.org/wiki/UTF-8
//
//    Implemented as a recursive descent parser based on a simple state machine
//    copyright 2005 Maarten Meijer
//
//    This cries out for a C-implementation to be included in PHP core
//
   function valid_1byte($char) {
       if(!is_int($char)) return false;
       return ($char & 0x80) == 0x00;
   }

   function valid_2byte($char) {
       if(!is_int($char)) return false;
       return ($char & 0xE0) == 0xC0;
   }

   function valid_3byte($char) {
       if(!is_int($char)) return false;
       return ($char & 0xF0) == 0xE0;
   }

   function valid_4byte($char) {
       if(!is_int($char)) return false;
       return ($char & 0xF8) == 0xF0;
   }

   function valid_nextbyte($char) {
       if(!is_int($char)) return false;
       return ($char & 0xC0) == 0x80;
   }

   function valid_utf8($string) {
       $len = strlen($string);
       $i = 0;
       while( $i < $len ) {
           $char = ord(substr($string, $i++, 1));
           if(valid_1byte($char)) {    // continue
               continue;
           } else if(valid_2byte($char)) { // check 1 byte
               if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                   return false;
           } else if(valid_3byte($char)) { // check 2 bytes
               if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                   return false;
               if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                   return false;
           } else if(valid_4byte($char)) { // check 3 bytes
               if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                   return false;
               if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                   return false;
               if(!valid_nextbyte(ord(substr($string, $i++, 1))))
                   return false;
           } // goto next char
       }
       return true; // done
   }

这是核心代码,用来实现编码方式的判断...

function iconvs($str) {
if(valid_utf8($str)){
return iconv("UTF-8","GB2312",$str);
}else{
return $str;
}
}

这是使用方法,将你传得的参数 先编码,解码后传入到 iconvs里面,就能实现 所有传递的参数均为 GB2312了..


Tags - uri编码 , gb2312 , utf-8 , google , baidu
文章来源:http://www.urlt.cn/blog/read.php?24

posted on 2008-12-26 14:59  小盗  阅读(166)  评论(0编辑  收藏  举报

导航