首页 > 计算机技术 > 后端开发 > PHP

PHP如何对中文正确截子串

原创 lihf8515 2025年01月21日 10:13
来源:本站 阅读:617

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

/**
 * 截子串
 */
function cc_substr($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;
}
作者
昵称:君子如兰
注册时间:2025-01-31 02:47:34
最近更新:2026-01-24 17:01:06
文章总数:94篇
原创 88篇   转载 6篇
友情链接: 海峰收银系统  
Copyright © 2025 hfsoft.top All Rights Reserved.
中华人民共和国工业和信息化部ICP备案序号:皖ICP备2025073039号