utf-8格式的文本在進(jìn)行字符串截取時(shí)容易出現(xiàn)截到一部分的情況,而且容易出現(xiàn)亂碼,這一個(gè)比較簡(jiǎn)單的函數(shù),需要php開啟mbstring擴(kuò)展 

$text是要截取的文本,$length是截取的長(zhǎng)度,$suffix表示是否截取后帶省略號(hào)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
     * 字符串截取,支持中文和其他編碼
     * @static
     * @access public
     * @param string $str 需要轉(zhuǎn)換的字符串
     * @param string $start 開始位置
     * @param string $length 截取長(zhǎng)度
     * @param string $charset 編碼格式
     * @param string $suffix 截?cái)囡@示字符
     * @return string
     */
    staticpublicfunctionmsubstr($str,$start=0,$length,$charset="utf-8",$suffix=true) {
        if(function_exists("mb_substr"))
            $slice= mb_substr($str,$start,$length,$charset);
        elseif(function_exists('iconv_substr')) {
            $slice= iconv_substr($str,$start,$length,$charset);
        }else{
            $re['utf-8']   ="/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
            $re['gb2312'] ="/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
            $re['gbk']    ="/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
            $re['big5']   ="/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
            preg_match_all($re[$charset],$str,$match);
            $slice= join("",array_slice($match[0],$start,$length));
        }
        return$suffix?$slice.'.':$slice;
    }
轉(zhuǎn)載請(qǐng)注明來源:一個(gè)php寫的截取字符串的函數(shù)

  哈爾濱品用軟件有限公司致力于為哈爾濱的中小企業(yè)制作大氣、美觀的優(yōu)秀網(wǎng)站,并且能夠搭建符合百度排名規(guī)范的網(wǎng)站基底,使您的網(wǎng)站無需額外費(fèi)用,即可穩(wěn)步提升排名至首頁。歡迎體驗(yàn)最佳的哈爾濱網(wǎng)站建設(shè)。