文章截取,显示第一张图片,不产生乱码的方法

 $body_len = 135;
        if(strpos($blog['Body'],"<img") !== false){
          $startStr = strstr($blog['Body'],"<img");
          $endPos =   strpos($startStr,"/>");
          $imgStr = substr($startStr,0,$endPos+2);
        }//把第一张照片给提取出来
         if(!$imgStr){
            $body_len += 56;
        }
        $summary = strip_tags($blog['Body']);//去掉所有的标签

        $summary = str_replace('&nbsp;','',$summary); //去掉&nbsp;
        $summary = str_replace(' ','',$summary);//去掉所有空格
        $summary = preg_replace('//r|/n/', '', $summary); //去掉换行
        if(strlen($summary) > $body_len){
            $summary = ms_utf8_substr($summary,$body_len);//截取,如果直接用substr的话,因为中文字符的问题,会产生乱码。
            $summary .= "...";
        }

 

function ms_utf8_substr($string,$length,$encode = 0) {//核心方法
    // 增加对html编码的 先解码,再截断,再编码的支持。
    if ($encode){
        $string = htmlspecialchars_decode($string);
    }
    $words = 0;
    $n = 0;
    while ($n < strlen($string) && $words < $length ) {
        $t = ord($string[$n]);
        if($t == 9 || $t == 10 || (32 <= $t && $t <= 127)) {
            $n++;
            $words ++;
        } elseif(192 <= $t && $t <= 223) {
            $n += 2;
            $words += 2;
        } elseif(224 <= $t && $t <= 239) {
            $n += 3;
            $words += 2;
        } elseif(240 <= $t && $t <= 247) {
            $n += 4;
            $words += 2;
        } elseif(248 <= $t && $t <= 251) {
            $n += 5;
            $words += 2;
        } elseif($t == 252 || $t == 253) {
            $n += 6;
            $words += 2;
        } else {
            $n++;
            $words ++;
        }
    }
    $wordscut = substr($string, 0, $n);
    if ($encode){
        $wordscut = htmlspecialchars($wordscut);
    }
    return $wordscut;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值