PHP的GBK字符處理函數

//例一:輸出$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參數,所有該字符後面的字符串都無法被保存。
===================================================================

發佈了27 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章