程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> php按字符無亂碼截取中文的方法

php按字符無亂碼截取中文的方法

編輯:PHP綜合

本文實例講述了php按字符無亂碼截取中文的方法。分享給大家供大家參考。具體實現方法如下:

<?php
//$str 待截取的字符串
//$len 截取的字符個數
//$chars 已經截取的字符數
//$res  保存的字符串
//$chars 保存已經截取的字符串個數
//$offset 截取的偏移量
//$length 字符串的字節數
//若$len>$str的字符個數,造成無謂的while循環,($offset<$length限定)
function utf8sub($str,$len){
  if($len<=0){
    return ;
  }
  $res="";
  $offset=0;
  $chars=0;
  $length=strlen($str);
  while($chars<$len && $offset<$length){
    $hign=decbin(ord(substr($str,$offset,1)));
      if(strlen($hign)<8){
        $count=1;
      }elseif(substr($hign,0,3)=="110"){
        $count=2;
      }elseif(substr($hign,0,4)=="1110"){
        $count=3;
      }elseif(substr($hign,0,5)=="11110"){
        $count=4;
      }elseif(substr($hign,0,6)=="111110"){
        $count=5;
      }elseif(substr($hign,0,7)=="1111110"){
        $count=6;
      }
    $res.=substr($str,$offset,$count);
    $offset+=$count;
    $chars+=1;
  }
  return $res;
}
function utf8sub1($str,$len){
  $chars=0;
  $res="";
  $offset=0;
  $length=strlen($str);
  while($chars<$len && $offset<$length){
    $hign=decbin(ord(substr($str,$offset,1)));
    if(strlen($hign)<8){
      $count=1;
    }elseif($hign & "11100000"=="11000000"){
      $count=2;
    }elseif($hign & "11110000"=="11100000"){
      $count=3;
    }elseif($hign & "11111000"=="11110000"){
      $count=4;
    }elseif($hign & "11111100"=="11111000"){
      $count=5;
    }elseif($hign & "11111110"=="11111100"){
      $count=6;
    }
    $res.=substr($str,$offset,$count);
    $chars++;
    $offset+=$count;
  }
  return $res;
}
$a="中華ah人民hdj";
echo utf8sub($a,5);
?>

希望本文所述對大家的php程序設計有所幫助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved