127 判断是否为汉字的首字节,是就一次取走整个汉字(gb2312 一个汉字占两个字节,UTF-8 占三个字节,后者需要把拼接改成连取三个字节),否则取单个 ASCII 字符,直到凑够长度。这个精简实现要注意编码差异,只适用于 gb2312 或按上述方式改造后用于 UTF-8,本质上是通过判断字节高位来避免把汉字截半,从而解决乱码问题。">

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

标点符 2010-04-06 13:54:46 累计浏览 4,034 次

下面的代码是来自于Sablog(http://www.sablog.net/)

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];
原图已失效

同分类推荐文章

  1. NGINX 1.31.7: Native GeoIP2 support, HTTP/2 priorities, and QUIC improvements (2026-11-13 23:40:02)
  2. 说说广场 API 0.31.0 版的调用代码说明 (2026-11-13 19:10:02)
  3. NGINX Routing on HTTP Request Body (2026-10-27 14:10:42)

查看更多 后端 文章 →

建议继续学习

  1. 使用gettext来支持PHP的多语言 (累计阅读 39,699)
  2. WordPress插件开发 -- 在插件使用数据库存储数据 (累计阅读 29,566)
  3. Paypal接口详细代码(PHP版,非API接口) (累计阅读 19,818)
  4. 我的PHP,Python和Ruby之路 (累计阅读 13,718)
  5. include(“./file.php”)和include(“file.php”)区别 (累计阅读 13,270)
  6. 15个最好的免费开源电子商务平台 (累计阅读 12,947)
  7. Redis消息队列的若干实现方式 (累计阅读 12,535)
  8. 到底什么是MVC? (累计阅读 12,382)
  9. 整理了一份招PHP高级工程师的面试题 (累计阅读 12,218)
  10. Rolling cURL: PHP并发最佳实践 (累计阅读 11,969)