两个截取字符的函数(解决了汉字乱码问题)

function get_word($content,$length,$more=1) {
 if(!$more){
  $length=$length+2;
 }
 if($length>10){
  $length=$length-2;
 }
 if($length && strlen($content)>$length){
  $num=0;
  for($i=0;$i<$length-1;$i++) {
   if(ord($content[$i])>127){
    $num++;
   }
  }
  $num%2==1 ? $content=substr($content,0,$length-2):$content=substr($content,0,$length-1);
  $more && $content.=’..’;
 }
 return $content;
}

 

 

function cut_string($str, $maxlen) {
 $width = Array(
  0, 12, 4, 4, 4, 6, 6, 10, 8, 4, 5, 5, 6, 6, 4, 6, 4, 6, 6, 6, 6,
  6, 6, 6, 6, 6, 6, 6, 4, 4, 8, 6, 8, 6, 12, 8, 8, 9, 8, 8, 7, 9,
  8, 3, 6, 8, 7, 11, 9, 9, 8, 9, 8, 8, 8, 8, 8, 10, 8, 8, 8, 6, 11,
  6, 6, 6, 4, 7, 7, 7, 7, 7, 3, 7, 7, 3, 3, 6, 3, 11, 7, 7, 7, 7,
  4, 7, 3, 7, 6, 10, 7, 7, 7, 6, 6, 6, 9, 0);

 $str_buffer = “”;
 $len_buffer = 0;
 $count = 0;

 $str_len = strlen($str);

 $maxlen = $width[1] * $maxlen / 2;

 while( $count < $str_len )
 {
  $asc = ord(substr($str, $count, 1));

  if( $asc > 127 )
  {
   $len_buffer += $width[1];
   if( $len_buffer > $maxlen )
   {
    $str_buffer .= “..”;
    break;
   }
   $str_buffer .= substr($str, $count, 2);
   $count += 2;
  }
  else
  {
   $len_buffer += $width[$asc-30];
   if( $len_buffer > $maxlen )
   {
    $str_buffer .= “..”;
    break;
   }
   $str_buffer .= substr($str, $count, 1);
   $count += 1;
  }
 }

 return $str_buffer;
}
echo cut_string(“南京晓庄学院,小小木同!”,17).”<br>”;

发表评论

电子邮件地址不会被公开。 必填项已用*标注