Discuz截取字符串

DZ截取字符串个人觉得比较好,特附上注释分析。

/** $string 要截取的字符串 $length 保留多少个字节 $dot 结尾字符 */

function cutstr($string, $length, $dot = ‘ …’) {

if(strlen($string) <= $length) {// 如果字符串小于要给出的保留数就直接输出

return $string;

}

$pre = chr(1);

$end = chr(1);

// 把原程序中htmlspecialchars转换了的字符还原

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

$strcut = ”; // 初始输出变量

// 如果是utf-8编码(这个判断有点不全,有可能是utf8)

if(strtolower(CHARSET) == ‘utf-8’) {

// 初始连续循环指针$n,最后一个字位数$tn,目前取到的字节数($noc都+2没看明白是什么意//义)

$n = $tn = $noc = 0;

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

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

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

// 如果是英语半角符号等,$n指针后移1位,$tn最后字是1位

$tn = 1; $n++; $noc++;

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

// 如果是二字节字符$n指针后移2位,$tn最后字是2位

$tn = 2; $n += 2; $noc += 2;

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

//如果是三字节(可以理解为中字词),$n后移3位,$tn最后字是3位

$tn = 3; $n += 3; $noc += 2;

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

$tn = 4; $n += 4; $noc += 2;

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

$tn = 5; $n += 5; $noc += 2;

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

$tn = 6; $n += 6; $noc += 2;

} else {

$n++;

}

// 超过了要取的数就跳出连续循环

if($noc >= $length) {

break;

}

// 这个地方是把最后一个字去掉,以备加$dot

}

if($noc > $length) {

$n -= $tn;

}

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

} else {

// 并非utf-8编码的全角就后移2位

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

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

}

}

// 再将特殊html转换(不明白有htmlspecialchars函数为什么不用)

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

$pos = strrpos($strcut, chr(1));

if($pos !== false) {

$strcut = substr($strcut,0,$pos);

}

return $strcut.$dot; // 最后把截取加上$dot输出

}

再长的路,一步步也能走完,再短的路,不迈开双脚也无法到达。

Discuz截取字符串

相关文章:

你感兴趣的文章:

标签云: