PHP的GBK字符处理函数

来源:互联网 发布:人民的名义 知乎 编辑:程序博客网 时间:2024/06/05 15:10

//例一:输出$explod_array[3]字串中的每一个字符
for($a=0;$a<mb_strlen($explod_array[3]);$a++){
//echo "<br/>".gb_substr2($explod_array[3],$a,1);
if(preg_match("/[/x80-/xff]/", substr($explod_array[3], $a, 1))){
echo "/".substr($explod_array[3],$a,2);
$a++;
}else{
echo "/".substr($explod_array[3],$a,1);
}
}


//例二:判断内容里有没有中文-GBK (PHP)
function check_is_chinese($s){
return preg_match('/[/x80-/xff]./', $s);
}

//例三:获取字符串长度-GBK (PHP)
function gb_strlen($str){
$count = 0;
for($i=0; $i<strlen($str); $i++){
$s = substr($str, $i, 1);
if (preg_match("/[/x80-/xff]/", $s)) ++$i;
++$count;
}
return $count;
}


//例四:截取字符串字串-GBK (PHP)
function gb_substr($str, $len){
$count = 0;
for($i=0; $i<strlen($str); $i++){
if($count == $len) break;
if(preg_match("/[/x80-/xff]/", substr($str, $i, 1))) ++$i;
++$count;
}
return substr($str, 0, $i);
}

//例五:截取字符串字串-GBK (PHP)
function gb_substr2($str,$position, $len){
if($position < 0) return;
$count = 1;
$poscount=0;
$length=1;
$pos=0;
$ispos=false;
for($i=0; $i<strlen($str); $i++){
if(preg_match("/[/x80-/xff]/", substr($str, $i, 1))) ++$i; //判断若是中文字符,多加一字节
if($count==$position){$pos=$i+1;$poscount=$count;$ispos=true;} //截取字符串的实际字节开始位置
if($ispos&&($count-$poscount)==$len){//截取字符串的实际字节长度
$length=$i-$pos+1;
break;
}
++$count;
}
return substr($str, $pos, $length);
}

================字符转换==========================================
iconv函数库能够完成各种字符集间的转换,是PHP编程中不可缺少的基础函数库。
windows 下
最近再做一个小偷程序,需要用到iconv函数把抓取过来的utf-8编码的页面转成gb2312,发现只有用iconv函数把抓取过来的数据一转码数据 就会无缘无故的少一些。让我郁闷了一会儿,去网上一查资料才知道这是iconv函数的一个bug.iconv在转换字符“-”到gb2312时会出错
解决方法很简单,就是在需要转成的编码后加“//IGNORE”也就是iconv函数第二个参数后。如下:
以下为引用的内容:
iconv(“utf-8”,“gb2312//IGNORE”,$data)
ignore的直接意思就是忽略,在此为忽略转换时的错误,如果没有ignore参数,所有该字符后面的字符串都无法被保存。
===================================================================

原创粉丝点击