解决使用mb_substr截取字符串时中文乱码的问题 注:mb_substr可以用来截取纯中文字符串,但是当中文字符串中含有数字或者英文字符或者中文状态下一个标点符号时会出现截取时中文乱码问题,因此这个函数就是用来解决这个问题的。 说明:经过个人测试,没有发现
解决使用mb_substr截取字符串时中文乱码的问题
/**
* @author zhangqiang
* 中英文字符截取函数,要求汉字字符编码必须为utf-8
*
* @param int $offset 跳过的字符个数
* @param int $length 截取的字符数个数
* @return $ret 返回截取后的字符串
*/
function zh_substr($str, $offset, $length = -1) {
$ret = '';
$bytelen = mb_strlen($str); //字符串的字节数
$start = 0;
$end = 0;
$nums = 0;
$count = 1;
for ( $i = 0; $i < $bytelen; $i++ ) {
if ( $nums == $offset ) {
$start = $i;
break;
}
if ( ord($str{$i}) > 0x80 || $count > 1 ) { //汉字
if ( $count % 3 === 0 ) { //统计出一个汉字
$nums += 1;
$count = 1;
} else {
$count += 1;
}
continue;
}
$nums += 1; //统计出一个英文
}
$nums = 0;
$count = 1;
for ( $i = $start; $i < $bytelen; $i++ ) {
if ( $nums == $length ) {
break;
}
if ( ord($str{$i}) > 0x80 || $count > 1 ) { //汉字
if ( $count % 3 === 0 ) { //统计出一个汉字
$nums += 1;
$count = 1;
$end += 3;
} else {
$count += 1;
}
continue;
}
$nums += 1; //统计出一个英文
$end += 1;
}
$ret = mb_substr($str, $start, $end);
return $ret;
}
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号