关于discuzx里面的字符串截取函数cutstr

来源:互联网 发布:php从入门到精通怎么样 编辑:程序博客网 时间:2024/05/16 01:11

function cutstr($string, $length, $dot = ' ...') {

if(strlen($string) <= $length) {

return $string;

}

 

$pre = '{%';

$end = '%}';

$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), $string);

 

$strcut = '';

if(strtolower(CHARSET) == 'utf-8') {

        /*

         * $n为字符数组下标

         */

$n = $tn = $noc = 0;

while($n < strlen($string)) {

 

$t = ord($string[$n]);

if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {

$tn = 1; $n++; $noc++;  //一个字节

} elseif(194 <= $t && $t <= 223) {

$tn = 2; $n += 2; $noc += 2;    //2个字节 $n移动两位 $noc取长度2  (110xxxxx 10xxxxxx)

} elseif(224 <= $t && $t <= 239) {

$tn = 3; $n += 3; $noc += 2;    //3个字节 $n移动3为 $noc取长度2  (1110xxxx 10xxxxxx 10xxxxxx)

} elseif(240 <= $t && $t <= 247) {

$tn = 4; $n += 4; $noc += 2;    //4个字节 $n移动4为 $noc取长度2  (11110xxx 10xxxxxx 10xxxxxx 10xxxxxx)

} elseif(248 <= $t && $t <= 251) {

$tn = 5; $n += 5; $noc += 2;    //5个字节 $n移动5为 $noc取长度2  (111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx)

} elseif($t == 252 || $t == 253) {

$tn = 6; $n += 6; $noc += 2;    //6个字节 $n移动6为 $noc取长度2  (1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx)

} else {

$n++;

}

            //总长超出则退出

if($noc >= $length) {

break;

}

 

}

//截取最后结果超出部分

if($noc > $length) {

$n -= $tn;

}

 

$strcut = substr($string, 0, $n);

 

} else {

//双字节截取

for($i = 0; $i < $length; $i++) {

$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];

}

}

 

$strcut = str_replace(array($pre.'&'.$end, $pre.'"'.$end, $pre.'<'.$end, $pre.'>'.$end), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);

 

return $strcut.$dot;

}