substr,mb_substr,mb_strcut,详解与中文字符串的截取无乱码

substr截取中文字符串会出现乱码,substr是按照单字节截取的,

mb_substr,mb_strcut都可以截取中文字符串,其中mb_substr是按照字符的个数截取(包括中文字符),mb_strcut是按照字节截取;

$str='水电费22sf223飞说的法士大夫24234是福施福士大夫';
echo mb_strcut($str, 0, 17, 'utf-8').'1
';//输出:水电费22sf223 echo mb_strcut($str, 3, 17, 'utf-8').'2
';//输出:电费22sf223飞 echo mb_strcut($str, -3, -2, 'utf-8').'3
';//输出:空值 echo mb_strcut($str, -3, 2, 'utf-8').'4
';//输出:空值 echo mb_strcut($str, 3, -2, 'utf-8').'5
';//输出:电费22sf223飞说的法士大夫24234是福施福士大 $str='水电费22sf223飞说的法士大夫24234是福施福士大夫'; echo mb_substr($str, 0, 17, 'utf-8').'
';//输出:水电费22sf223飞说的法士大夫 echo mb_substr($str, 3, 17, 'utf-8').'
';//输出:费22sf223飞说的法士大夫242 echo mb_substr($str, -3, -2, 'utf-8').'
';//输出:福士 echo mb_substr($str, -3, 2, 'utf-8').'
';//输出:士大 echo mb_substr($str, 3, -2, 'utf-8').'
';//输出:22sf223飞说的法士大夫24234是福施福士 echo "

"; $str='234sdh24324shkfsdfsdf'; echo substr($str,0,2).'
';//输出:23 echo substr($str,3,3).'
';//输出:sdh echo substr($str,-7,3).'
';//输出:fsd echo substr($str,-3).'
';//输出:sdf echo substr($str,-3,-6).'
';//输出:空值 echo substr($str,-6,-3).'
';//输出:sdf echo substr($str,3,-2).'
';//输出:sdh24324shkfsdfs

 php扩展函数一般比自定义的字符串函数速度快,比如下面这个自定义函数就比php自带的函数慢5到6倍;

$str='水电费22sf223飞说的法士大夫24234是福施福士大夫';
echo cutstr($str, 17, $suffix = '');
function cutstr($string, $length, $suffix = '')
{
    $p    =    0;
    $j    =    0;
    if($string == "")
    {
        return "";
    }
    preg_match_all('/([x41-x5a,x61-x7a,x30-x39])/', $string, $letter); //字母
    $string_len = strlen($string);
    $let_len = count($letter[0]);
    if($string_len == $let_len)
    {
        //没有汉字
        $len = floor($length / 2);
        if($string_len > $len)
            return substr($string, 0, $len) . $suffix;
        else 
            return substr($string, 0, $len);
    }
    $length_tmp    =    ($string_len - $let_len * 2) + $let_len * 2;
    if($length_tmp > $length)
    {
        for ($k=0;$k<=($length-3);$k++)
        {
            $j++;
            if($j    >    ($length-3))
            {
                break;
            }
            if (ord(substr($string,$k,1)) >= 129)
            {
                $k+=2;
                $j+=2;
            }
            else
            {
                $p++;
            }
            if($p    ==    2)
            {
                $j++;
                $p    =    0;
            }
        }
        $string = substr($string, 0, $k);
    }
    $string    =    str_replace("","
",$string); $string = str_replace("","
",$string); $string = str_replace("<…","
",$string); if($string_len > strlen($string)) return $string . $suffix; else return $string; }

 

转载于:https://www.cnblogs.com/anxuexi/archive/2013/04/02/2995232.html

你可能感兴趣的:(substr,mb_substr,mb_strcut,详解与中文字符串的截取无乱码)