PHP字符串截取函数(解决中文乱码问题!支持UTF-8和GB2312)


Posted on February 12, 2009


 /*********************************************************************
    函数名称:CutString
    函数作用:字符串截取函数,双字节文字当成两个文字处理
    使用方法:CutString("我是中国人",5);
    参数说明:
    $str 需要处理的字符串
    $len 为截取的长度(即字数)
    $encode 文字编码支持UTF-8和GB2312
    ********************************************************************
*/
   
public static function CutString($str,$len,$encode=´utf-8´/*$encode=´GB2312´*/)
    {
       
if(strlen($str)<=$len or $len<1)
        {
           
return $str;
        }
       
else
        {
           
for($i=0;$i<=$len;$i++)
            {
               
$temp_str=substr($str,0,1);
               
if(ord($temp_str)>127)
                {
                   
$i++;
                   
if($i<=$len)
                    {
                       
if($encode==´utf-8´)
                        {
                           
$new_str[]=substr($str,0,3);
                           
$str=substr($str,3);
                        }
                       
else
                        {
                           
$new_str[]=substr($str,0,2);
                           
$str=substr($str,2);
                        }
                    }
                }
               
else
                {
                   
$new_str[]=substr($str,0,1);
                   
$str=substr($str,1);
                }
            }
           
return join($new_str)."";
        }
    }


另外一种不错的方法:

<?php
/*
Utf-8、gb2312都支持的汉字截取函数
cut_str(字符串, 截取长度, 开始长度, 编码);
编码默认为 utf-8
开始长度默认为 0
*/

function cut_str($string, $sublen, $start = 0, $code = ´UTF-8´)
{
    if($code == ´UTF-8´)
    {
       $pa ="/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
        preg_match_all($pa, $string, $t_string);        if(count($t_string[0]) - $start > $sublen) return join(´´, array_slice($t_string[0], $start, $sublen))."...";
        return join(´´, array_slice($t_string[0], $start, $sublen));
    }
    else
    {
        $start = $start*2;
        $sublen = $sublen*2;
        $strlen = strlen($string);
        $tmpstr = ´´;        for($i=0; $i<$strlen; $i++)
        {
            if($i>=$start && $i<($start+$sublen))
            {
                if(ord(substr($string, $i, 1))>129)
                {
                    $tmpstr.= substr($string, $i, 2);
                }
                else
                {
                    $tmpstr.= substr($string, $i, 1);
                }
            }
            if(ord(substr($string, $i, 1))>129) $i++;
        }
        if(strlen($tmpstr)<$strlen ) $tmpstr.= "...";
        return $tmpstr;
    }
}

$str = "abcd需要截取的字符串";
echo cut_str($str, 8, 0, ´gb2312´);
?>


标签:N/A

 

在线学习答案查询入口
微信扫码联系
微信扫码联系