最新消息:

PHP截取汉字出现乱码的解决方法

php admin 3136浏览 0评论
function trimmed_title($text, $limit=12) {
 if ($limit) {
  $val = csubstr($text, 0, $limit);
  return $val[1] ? $val[0]."..." : $val[0];
 } else {
  return $text;
 }
}
function csubstr($text, $start=0, $limit=12) {
 if (function_exists(’mb_substr’)) {
  $more = (mb_strlen($text, ’UTF-8’) > $limit) ? TRUE : FALSE;
  $text = mb_substr($text, 0, $limit, ’UTF-8’);
  return array($text, $more);
 } elseif (function_exists(’iconv_substr’)) {
  $more = (iconv_strlen($text) > $limit) ? TRUE : FALSE;
  $text = iconv_substr($text, 0, $limit, ’UTF-8’);
  return array($text, $more);
 } else {
  preg_match_all("/[x01-x7f]|[xc2-xdf][x80-xbf]|xe0[xa0-xbf][x80-xbf]|[xe1-xef][x80-xbf][x80-xbf]|xf0[x90-xbf][x80-xbf][x80-xbf]|[xf1-xf7][x80-xbf][x80-xbf][x80-xbf]/", $text, $ar);
  if(func_num_args() >= 3) {
   if (count($ar[0])>$limit) {
    $more = TRUE;
    $text = join("",array_slice($ar[0],0,$limit))."...";
   } else {
    $more = FALSE;
    $text = join("",array_slice($ar[0],0,$limit));
   }
  } else {
   $more = FALSE;
   $text =  join("",array_slice($ar[0],0));
  }
  return array($text, $more);
 }
}
function csubstr ($text, $limit) {
$s = ’’;
for($i=0;$i< $limit-3;$i++) {
$s .= ord($text[$i])>127 ? $text[$i].$text[++$i] : $text[$i];
}
return $s;
}

以上仅适用于gb2312 编码(gb2312中,一个汉字占两个字节),如果是UTF-8(UTF-8中一个汉字占三个字节)需要把第4行改为:

$s .= ord($text[$i])>127 ? $text[$i].$text[++$i].$text[++$i] : $text[$i];

转载请注明:爱开源 » PHP截取汉字出现乱码的解决方法

您必须 登录 才能发表评论!