多个PHP中文字符串截取函数

2020-01-24 23:18栏目:编程
TAG:

复制代码 代码如下:

复制代码 代码如下:
function sysSubStr($string,$length,$append = false)
{
    if(strlen($string) <= $length )
    {
        return $string;
    }
    else
    {
        $i = 0;
        while ($i < $length)
        {
            $stringTMP = substr($string,$i,1);
            if ( ord($stringTMP) >=224 )
            {
                $stringTMP = substr($string,$i,3);
bob体育app,                $i = $i + 3;
            }
            elseif( ord($stringTMP) >=192 )
            {
                $stringTMP = substr($string,$i,2);
                $i = $i + 2;
            }
            else
            {
                $i = $i + 1;
            }
            $stringLast[] = $stringTMP;
        }
        $stringLast = implode("",$stringLast);
        if($append)
        {
            $stringLast .= "...";
        }
        return $stringLast;
    }
}

//截取utf8字符串 function utf8Substr { return preg_replace('#^(?:[x00-x7F]|[xC0-xFF][x80-xBF]+){0,'.$from.'}'. '((?:[x00-x7F]|[xC0-xFF][x80-xBF]+){0,'.$len.'}).*#s', '$1',$str); }

$string = "简明今世法力 —— 静心于网络主流的种种本领";
$length = "27";
$append = true;
echo sysSubStr($string,$length,$append);
// 输出
// 简明现代法力 —— 专...
?>

截取GB2312汉语字符串: 复制代码 代码如下:
//截取中文字符串
function mysubstr($str, $start, $len) {
    $tmpstr = "";
    $strlen = $start + $len;
    for($i = 0; $i < $strlen; $i++) {
        if(ord(substr($str, $i, 1)) > 0xa0) {
            $tmpstr .= substr($str, $i, 2);
            $i++;
        } else
            $tmpstr .= substr($str, $i, 1);
    }
    return $tmpstr;
}
?>

截取utf8编码的多字节字符串: 复制代码 代码如下:
//截取utf8字符串
function utf8Substr($str, $from, $len)
{
    return preg_replace('#^(?:[x00-x7F]|[xC0-xFF][x80-xBF]+){0,'.$from.'}'.
                       '((?:[x00-x7F]|[xC0-xFF][x80-xBF]+){0,'.$len.'}).*#s',
                       '$1',$str);
}
?>

UTF-8、GB2312都帮衬的方块字截取函数: 复制代码 代码如下:
/*
Utf-8、gb2312都扶助的汉字截取函数
cut_str(字符串, 截取长度, 开头长度, 编码卡塔尔;
编码默感觉 utf-8
始于长度暗中同意为 0
*/

版权声明:本文由bob体育app发布于编程,转载请注明出处:多个PHP中文字符串截取函数