GBK:


 
   
  1. <?php

  2. function mysubstr($str, $start, $len) {

  3. $tmpstr = "";

  4. $strlen = $start + $len;

  5. for($i = 0; $i < $strlen; $i++) {

  6. if(ord(substr($str, $i, 1)) > 0xa0) {

  7. $tmpstr .= substr($str, $i, 2);

  8. $i++;

  9.        } else

  10. $tmpstr .= substr($str, $i, 1);

  11.    }

  12. return$tmpstr;

  13. }

  14. ?>


今天发现(2014-02-11)上面方法不靠谱,还是出现了乱码,用下面这个就可以了:


function sysSubStr($String,$Length,$Append = false)  
{  
if (strlen($String) <= $Length )  
{  
return $String;  
}  
else 
{  
$I = 0;  
while ($I < $Length)  
{  
$StringTMP = substr($String,$I,1);  
if ( ord($StringTMP) >=224 )  
{  
$StringTMP = substr($String,$I,3);  
$I = $I + 3;  
}  
elseif( ord($StringTMP) >=192 )  
{  
$StringTMP = substr($String,$I,2);  
$I = $I + 2;  
}  
else 
{  
$I = $I + 1;  
}  
$StringLast[] = $StringTMP;  
}  
$StringLast = implode("",$StringLast);  
if($Append)  
{  
$StringLast .= "...";  
}  
return $StringLast;  
}  
}





UTF-8:


 
   
  1. <?php

  2. function utfSubstr($str, $position, $length,$type=1){

  3. $startPos = strlen($str);

  4. $startByte = 0;

  5. $endPos = strlen($str);

  6. $count = 0;

  7. for($i=0; $i<strlen($str); $i++){

  8. if($count>=$position && $startPos>$i){

  9. $startPos = $i;

  10. $startByte = $count;

  11.   }

  12. if(($count-$startByte) >= $length) {

  13. $endPos = $i;

  14. break;

  15.   }

  16. $value = ord($str[$i]);

  17. if($value > 127){

  18. $count++;

  19. if($value>=192 && $value<=223) $i++;

  20. elseif($value>=224 && $value<=239) $i = $i + 2;

  21. elseif($value>=240 && $value<=247) $i = $i + 3;

  22. elsereturn self::raiseError("\"$str\" Not a UTF-8 compatible string", 0, __CLASS__, __METHOD__, __FILE__, __LINE__);

  23.   }

  24. $count++;

  25.  }

  26. if($type==1 && ($endPos-6)>$length){

  27. returnsubstr($str, $startPos, $endPos-$startPos);

  28.  }

  29. else{

  30. returnsubstr($str, $startPos, $endPos-$startPos);      

  31.  }

  32. }

  33. ?>