截取字符串,汉字占两个字节,字母占一个字节

时间:2022-09-07 22:43:36
/*
 * 页面编码必须为utf-8
 */
function esub($str, $length = 0, $ext = "...") {
     if ($length < 1) {
          return $str;
     }
     //计算字符串长度
     $strlen = (strlen($str) + mb_strlen($str, "UTF-8")) / 2;
     if ($strlen < $length) {
          return $str;
     }
     if (mb_check_encoding($str, "UTF-8")) {
          $str = mb_strcut(mb_convert_encoding($str, "GBK", "UTF-8"), 0, $length, "GBK");
          $str = mb_convert_encoding($str, "UTF-8", "GBK");
     } else {
          return "不支持的文档编码";
     }
     $str = rtrim($str, " ,.。,-——(【、;‘“??《<@");
     return $str . $ext;
}
$str = "L对每个人都说还好";