国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 網站 > 建站經驗 > 正文

php字符截取函數支持UTF8與GBK

2024-04-25 20:35:57
字體:
來源:轉載
供稿:網友

項目開發中,文字截取必不可少的,比如前段的文章標題,文章簡介什么的,都需要截取,有的截取函數,截取出來有亂碼,今天分享一個支持utf8和gbk都支持的函數

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

$strlen = strlen($string);

if($strlen <= $length) return $string;

$string = str_replace(array(' ','&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵',' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);

$strcut = '';

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

$length = intval($length-strlen($dot)-$length/3);

$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;

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

$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;

}

}

if($noc > $length) {

$n -= $tn;

}

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

$strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);

} else {

$dotlen = strlen($dot);

$maxi = $length - $dotlen - 1;

$current_str = '';

$search_arr = array('&',' ', '"', "'", '“', '”', '—', '<', '>', '·', '…','∵');

$replace_arr = array('&amp;','&nbsp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;',' ');

$search_flip = array_flip($search_arr);

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

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

if (in_array($current_str, $search_arr)) {

$key = $search_flip[$current_str];

$current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);

}

$strcut .= $current_str;

}

}

return $strcut.$dot;

}

 

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 石城县| 蒙城县| 天柱县| 太和县| 肥乡县| 贡觉县| 晋宁县| 易门县| 通化县| 仙游县| 慈利县| 喀什市| 清流县| 大埔县| 高州市| 周口市| 东城区| 镇巴县| 榕江县| 凉城县| 周至县| 象山县| 达尔| 罗江县| 颍上县| 宜章县| 拉孜县| 新绛县| 泽库县| 平泉县| 兰西县| 余干县| 团风县| 枣庄市| 花莲市| 茂名市| 玉环县| 正定县| 光山县| 桂阳县| 彭州市|