phpcms v9怎么截取英文字符串的长度呀

2024-11-17 03:41:39
推荐回答(2个)
回答1:

以下为截取代码:
/**
* 字符截取 支持UTF8/GBK
* @param $string
* @param $length
* @param $dot
*/
function str_cut($string, $length, $dot = '') {
$strlen = strlen($string);
if($strlen/2 <= $length) return $string;
$string = str_replace(array(' ',' ',' ',' ', '&', '"', ''', '“', '”', '—', '<', '>', '·', '…'), array(' ',' ',' ',' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
$strcut = '';
$n = $tn = $noc = 0;
if(strtolower(CHARSET) == 'utf-8') {
while($n < $strlen) {
$t = ord($string[$n]);
if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
$tn = 1; ++$n; $noc += 0.5;
} elseif(194 <= $t && $t <= 223) {
$tn = 2; $n += 2; $noc += 1;
} elseif(224 <= $t && $t <= 239) {
$tn = 3; $n += 3; $noc += 1;
} elseif(240 <= $t && $t <= 247) {
$tn = 4; $n += 4; $noc += 1;
} elseif(248 <= $t && $t <= 251) {
$tn = 5; $n += 5; $noc += 1;
} elseif($t == 252 || $t == 253) {
$tn = 6; $n += 6; $noc += 1;
} else {
++$n;
}
if($noc >= $length) {
if($n < $strlen) ++$noc;
break;
}
}
} else {
while($n < $strlen) {
if(ord($string[$n]) > 127) {
$tn = 2; $n += 2; $noc += 1;
} else{
$tn = 1; ++$n; $noc += 0.5;
}
if($noc >= $length) {
if($n < $strlen) ++$noc;
break;
}
}
}
if($noc > $length && !empty($dot)) {
$n -= $tn;
$strcut = substr($string, 0, $n);
$strcut .= $dot;
}else{
$strcut = substr($string, 0, $n);
}
$strcut = str_replace(array('&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array('&', '"', ''', '“', '”', '—', '<', '>', '·', '…'), $strcut);
return $strcut;
}
参考链接:http://www.cmsyou.com/support/92.html

回答2:

{str_cut(strip_tags($r[content]),100)} 按这种格式应该会成功的,,希望能帮到你