插件窝 干货文章 php中文字符串截取防止出现乱码

php中文字符串截取防止出现乱码

字符串截取 646    来源:插件窝    2019-08-22

网站开发过程中,文章描述需要常常需要用到截取指定长度的字符来保持样式的一致宽度,但是字符中有时候会存在标点符号和字母或者数字的组合,往往不能用3的倍数来做整除算长度,下面根据二进制封装了一个函数保证截取的字符串不会出现乱码报错

function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true)
{
   if (function_exists("mb_substr"))
       $slice = mb_substr($str, $start, $length, $charset);
   elseif (function_exists('iconv_substr')) {
       $slice = iconv_substr($str, $start, $length, $charset);
       if (false === $slice) {
           $slice = '';
       }
   } else {
       $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
       $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
       $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
       $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
       preg_match_all($re[$charset], $str, $match);
       $slice = join("", array_slice($match[0], $start, $length));
   }
   return $suffix ? $slice . '...' : $slice;
}

可以根据自己的需要传入开始和截取的指针和指定截取的长度