软件开发者和爱好者的知识分享社区
小财迷电脑收银系统 关于本站 写文章 免费注册
首页 > 计算机技术 > 后端开发 > PHP

PHP如何对中文正确截子串

原创 lihf8515于2025年01月21日 10:13发表
来源:本站 阅读:169

php自带的求子串函数只能处理英文字符,如果出现中文字符时,就会出现截取数量不正确的情况。我们有必要自己编写一个正确的函数处理它。下面给出自定义的求中文子串的函数。


/**
* 截子串
*/
function cc_msubstr($str, $start, $length, $charset="utf-8", $suffix=true)
{
if(function_exists("mb_substr"))
return mb_substr($str, $start, $length, $charset);
elseif(function_exists('iconv_substr')) {
return iconv_substr($str,$start,$length,$charset);
}
$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));
if($suffix) return $slice."…";
return $slice;
}
友情链接: 小财迷收银系统  
Copyright © 2025 海峰软件技术. All Rights Reserved.
中华人民共和国工业和信息化部ICP备案序号:皖ICP备2025073039号