PHP截取汉字出现乱码的解决方法
浏览:2481次 出处信息
下面的代码是来自于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];
建议继续学习:
- Vim 中截取部分内容保存到其他文件 (阅读:6262)
- windows下压缩包在linux解压乱码的解决办法 (阅读:4025)
- Linux screen窗口中文乱码问题 (阅读:3806)
- linux下vim的编译以及终端乱码的最终解决方案 (阅读:3403)
- java中文乱码解决之道(六)—–javaWeb中的编码解码 (阅读:2914)
- PHP截取图片的某个区域 (阅读:2799)
- 解决PHPMailer邮件标题中文乱码 (阅读:2504)
- 如何在PHP下载文件名中解决乱码 (阅读:2469)
- Smarty截取中文乱码的解决办法 (阅读:2386)
- java中文乱码解决之道(一)—–认识字符集 (阅读:2199)
QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习
扫一扫订阅我的微信号:IT技术博客大学习
<< 前一篇:使用SoapHeader实现Soap请求验证
后一篇:Smarty截取中文乱码的解决办法 >>
文章信息
- 作者:标点符 来源: 标点符
- 标签: 乱码 截取
- 发布时间:2010-04-06 13:54:46
建议继续学习
近3天十大热文
- [695] Go Reflect 性能
- [25] 正态分布的前世今生(一)
- [16] rsync同步的艺术
- [15] Cuckoo Filter:设计与实现
- [13] 关于RDS只读实例延迟分析
- [13] 什么是DNS劫持和DNS污染?
- [13] Linux Used内存到底哪里去了?
- [12] 公钥私钥加密解密数字证书数字签名详解
- [12] Linux内存中的Cache真的能被回收么?
- [11] Android应用内多进程的使用及注意事项