企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
~~~ /** * 字符串截取,支持中文和其他编码 * * @param string $str 需要转换的字符串 * @param string $start 开始位置 * @param string $length 截取长度 * @param string $suffix 截断显示字符 * @param string $charset 编码格式 * * @return string */ function re_substr($str, $start = 0, $length, $suffix = true, $charset = "utf-8") { if (function_exists("mb_substr")) { $slice = mb_substr($str, $start, $length, $charset); } elseif (function_exists('iconv_substr')) { $slice = iconv_substr($str, $start, $length, $charset); } 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)); } $omit = mb_strlen($str) >= $length ? '...' : ''; return $suffix ? $slice.$omit : $slice; } ~~~ ~~~ /** * 字符截取 * @param $string 需要截取的字符串 * @param $length 长度 * @param $dot */ function str_cut($sourcestr, $length, $dot = '...') { $returnstr = ''; $i = 0; $n = 0; $str_length = strlen($sourcestr); //字符串的字节数 while (($n < $length) && ($i <= $str_length)) { $temp_str = substr($sourcestr, $i, 1); $ascnum = Ord($temp_str); //得到字符串中第$i位字符的ascii码 if ($ascnum >= 224) { //如果ASCII位高与224, $returnstr = $returnstr . substr($sourcestr, $i, 3); //根据UTF-8编码规范,将3个连续的字符计为单个字符 $i = $i + 3; //实际Byte计为3 $n++; //字串长度计1 } elseif ($ascnum >= 192) { //如果ASCII位高与192, $returnstr = $returnstr . substr($sourcestr, $i, 2); //根据UTF-8编码规范,将2个连续的字符计为单个字符 $i = $i + 2; //实际Byte计为2 $n++; //字串长度计1 } elseif ($ascnum >= 65 && $ascnum <= 90) { //如果是大写字母, $returnstr = $returnstr . substr($sourcestr, $i, 1); $i = $i + 1; //实际的Byte数仍计1个 $n++; //但考虑整体美观,大写字母计成一个高位字符 } else { //其他情况下,包括小写字母和半角标点符号, $returnstr = $returnstr . substr($sourcestr, $i, 1); $i = $i + 1; //实际的Byte数计1个 $n = $n + 0.5; //小写字母和半角标点等与半个高位字符宽... } } if ($str_length > strlen($returnstr)) { $returnstr = $returnstr . $dot; //超过长度时在尾处加上省略号 } return $returnstr; } ~~~