欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php中文字符串截取函数支持多种编码

程序员文章站 2022-04-21 22:05:14
...
  1. /*

  2. * @todo 中文截取,支持gb2312,gbk,utf-8,big5
  3. * @http://bbs.it-home.org
  4. * @param string $str 要截取的字串
  5. * @param int $start 截取起始位置
  6. * @param int $length 截取长度
  7. * @param string $charset utf-8|gb2312|gbk|big5 编码
  8. * @param $suffix 是否加尾缀
  9. */
  10. function csubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)

  11. {
  12. if(function_exists("mb_substr"))
  13. return mb_substr($str, $start, $length, $charset);
  14. $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
  15. $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
  16. $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
  17. $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
  18. preg_match_all($re[$charset], $str, $match);
  19. $slice = join("",array_slice($match[0], $start, $length));
  20. if($suffix) return $slice."…";
  21. return $slice;
  22. }
  23. ?>
复制代码

以上代码,看着就牛X,要知道php的正则,那是相当强悍的。 复制以上代码,在你的机器上测试下吧,多动手,有助于快速提高编程水平。