找回密码
 注册加入

扫一扫,极速登录

QQ登录

只需一步,快速开始

搜索
查看: 6792|回复: 1

php截取字符串防乱码,支持各种编码

[复制链接]
发表于 2012-12-16 17:32:48 | 显示全部楼层 |阅读模式
摘自ThinkPHP类库中的功能,不过很好用,支持各种编码。
  1. /**
  2. +----------------------------------------------------------
  3. * 字符串截取,支持中文和其他编码
  4. +----------------------------------------------------------
  5. * @static
  6. * @access public
  7. +----------------------------------------------------------
  8. * @param string $str 需要转换的字符串
  9. * @param string $start 开始位置
  10. * @param string $length 截取长度
  11. * @param string $charset 编码格式
  12. * @param string $suffix 截断显示字符
  13. +----------------------------------------------------------
  14. * @return string
  15. +----------------------------------------------------------
  16. */
  17. function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true) {
  18.        if(function_exists("mb_substr"))
  19.            $slice = mb_substr($str, $start, $length, $charset);
  20.        elseif(function_exists('iconv_substr')) {
  21.            $slice = iconv_substr($str,$start,$length,$charset);
  22.        }else{
  23.            $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
  24.            $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
  25.            $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
  26.            $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
  27.            preg_match_all($re[$charset], $str, $match);
  28.            $slice = join("",array_slice($match[0], $start, $length));
  29.        }
  30.        return $suffix ? $slice.'...' : $slice;
  31.    }
复制代码
发表于 2013-3-17 18:54:14 来自手机 | 显示全部楼层
直接用系统函数mb_substr()不是更好
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册加入  

本版积分规则

Archiver|手机版|小黑屋|Discuz!扩展中心 ( 浙ICP备14042422号-1 )|网站地图QQ机器人

GMT+8, 2024-4-20 06:03 , Processed in 0.134577 second(s), 14 queries , Gzip On, Redis On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表