欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP截取中文

程序员文章站 2022-03-19 23:38:09
function subtitle($string,$length) {  if (mb_strwidth($string, 'utf8') &...

function subtitle($string,$length) {
 if (mb_strwidth($string, 'utf8') <= $length ){
  return $string;
 }else{
  $i = 0;
  $len_word = 0;
  while ($len_word < $length){
   $stringtmp = substr($string,$i,1);
   if ( ord($stringtmp) >=224 ){
    $stringtmp = substr($string,$i,3);
    $i = $i + 3;
    $len_word = $len_word + 2;
   }elseif( ord($stringtmp) >=192 ){
    $stringtmp = substr($string,$i,2);
    $i = $i + 2;
    $len_word = $len_word + 2;
   }else{
    $i = $i + 1;
    $len_word = $len_word + 1;
   }
   $stringlast[] = $stringtmp;
  }
  /* raywang edit it for dirk for (es/index.php)*/
  if (is_array($stringlast) && !empty($stringlast)){
   $stringlast = implode("",$stringlast);
   $stringlast .= "...";
  }
  return $stringlast;
 }
}