首页建站经验 php字符截取函数支持UTF8与GBK

php字符截取函数支持UTF8与GBK

项目开发中,文字截取必不可少的,比如前段的文章标题,文章简介什么的,都需要截取,有的截取函数,截取出来有乱码,今天分享一个支持utf8和gbk都支持的函数function str_cut($string, $…

项目开发中,文字截取必不可少的,比如前段的文章标题,文章简介什么的,都需要截取,有的截取函数,截取出来有乱码,今天分享一个支持utf8和gbk都支持的函数

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

$strlen = strlen($string);

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

$string = str_replace(array(' ',' ', '&', '"', ''', '“', '”', '—', '<', '>', '·', '…'), 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(' ', '&', '"', ''', '“', '”', '—', '<', '>', '·', '…'), $strcut);

} else {

$dotlen = strlen($dot);

$maxi = $length - $dotlen - 1;

$current_str = '';

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

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

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

}

 

本文来自网络,不代表1号站长-站长学院|资讯交流平台立场。转载请注明出处: https://www.1cn.cc/jianzhan/jingyan/17160.html
上一篇php如何post发送数据
下一篇 php文件下载函数
admin

作者: admin

这里可以再内容模板定义一些文字和说明,也可以调用对应作者的简介!或者做一些网站的描述之类的文字或者HTML!

为您推荐

评论列表()

    联系我们

    联系我们

    0898-88888888

    在线咨询: QQ交谈

    邮箱: email@wangzhan.com

    工作时间:周一至周五,9:00-17:30,节假日休息

    关注微信
    微信扫一扫关注我们

    微信扫一扫关注我们

    关注微博
    返回顶部