• php字符串标点等字符截取不乱吗 封装方法


    方法一:

    /**
      +----------------------------------------------------------
     * 功能:字符串截取指定长度
     * leo.li hengqin2008@qq.com
      +----------------------------------------------------------
     * @param string    $string      待截取的字符串
     * @param int       $len         截取的长度
     * @param int       $start       从第几个字符開始截取
     * @param boolean   $suffix      是否在截取后的字符串后跟上省略号
      +----------------------------------------------------------
     * @return string               返回截取后的字符串
      +----------------------------------------------------------
     */

    function cutStr($str, $len = 100, $start = 0, $suffix = 1) {
        $str = strip_tags(trim(strip_tags($str)));
        $str = str_replace(array(" ", " "), "", $str);
        $strlen = mb_strlen($str);
        while ($strlen) {
            $array[] = mb_substr($str, 0, 1, "utf8");
            $str = mb_substr($str, 1, $strlen, "utf8");
            $strlen = mb_strlen($str);
        }
        $end = $len + $start;
        $str = '';
        for ($i = $start; $i < $end; $i++) {
            $str.=$array[$i];
        }
        return count($array) > $len ? ($suffix == 1 ? $str . "&hellip;" : $str) : $str;
    }


    方法二:

    header("Content-type:text/html; charset=utf8");
    function cut_str($string, $sublen, $start = 0, $code = 'UTF-8') 

    if($code == 'UTF-8') 

    $pa ="/[x01-x7f]|[xc2-xdf][x80-xbf]|xe0[xa0-xbf][x80-xbf]|[xe1-xef][x80-xbf][x80-xbf]|xf0[x90-xbf][x80-xbf][x80-xbf]|[xf1-xf7][x80-xbf][x80-xbf][x80-xbf]/"; 
    preg_match_all($pa, $string, $t_string); if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen)); 
    return join('', array_slice($t_string[0], $start, $sublen)); 

    else 

    $start = $start*2; 
    $sublen = $sublen*2; 
    $strlen = strlen($string); 
    $tmpstr = ''; for($i=0; $i<$strlen; $i++) 

    if($i>=$start && $i<($start+$sublen)) 

    if(ord(substr($string, $i, 1))>129) 

    $tmpstr.= substr($string, $i, 2); 

    else 

    $tmpstr.= substr($string, $i, 1); 


    if(ord(substr($string, $i, 1))>129) $i++; 

    if(strlen($tmpstr)<$strlen ) $tmpstr.= ""; 
    return $tmpstr; 




    $str="我slskjd!fl是总那地方拉伸款到即发";


    echo cut_str($str, 8, 5); 





  • 相关阅读:
    ASFNU SC Day6
    ASFNU SC Day3
    ASFNU SC Day2
    ASFNU SC Day1
    2017-9-3 校内模拟T2取数win
    2017-9-3 校内模拟T1卡片card
    (补题)苗条的树(poj_3522)
    跳跳棋(9018_1563)(BZOJ_2144)
    Java之JSP和Servlet基础知识。
    JSP中的九大内置对象
  • 原文地址:https://www.cnblogs.com/blfshiye/p/4052033.html
Copyright © 2020-2023  润新知