[PHP] – 按長度截取字串(針對UTF-8)

來源:互聯網
上載者:User

代碼是看看規範又抄又改,希望是完美沒錯...

 

/********************************************************************* * * Func Name : SubStrEx * * Description : *     按長度截取字串 * * * Parameters : *     $sString[string] : 字串 *     $nLength[int] : 要取長度 *     $sDot[string="..."] : 截斷符 *     $sCharset[string="UTF-8"] : 編碼 * * Returns : [bool]儲存結果 * *********************************************************************/function SubStrEx ($sString, $nLength, $sDot = "...", $sCharset = "UTF-8") {    if (strlen($sString) <= $nLength) {        return $sString;    }    $sString = str_replace(array("&", "\"", "<", ">"), array("&", "\"", "<", ">"), $sString);    $sStrcut = "";    if (strtoupper($sCharset) == "UTF-8") {        $nPos = 0;        $nWordLen = 0;        $noc = 0;  // 單位元組字元+1,多位元組+2(將非單位元組字元的長度當做是2[應該是視覺感覺吧])        while ($nPos < strlen($sString)) {            $t = ord($sString[$nPos]);            if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {                $nWordLen = 1;                $noc++;            } elseif (194 <= $t && $t <= 223) {                $nWordLen = 2;                $noc += 2;            } elseif (224 <= $t && $t <= 239) {                $nWordLen = 3;                $noc += 2;            } elseif (240 <= $t && $t <= 247) {                $nWordLen = 4;                $noc += 2;            } elseif (248 <= $t && $t <= 251) {                $nWordLen = 5;                $noc += 2;            } elseif ($t == 252 || $t == 253) {                $nWordLen = 6;                $noc += 2;            } else {                $nWordLen = 0;            }                        $nPos += ($nWordLen > 0) ? $nWordLen : 1;            if ($noc >= $nLength) {                break;            }        }        if ($noc > $nLength) {            $nPos -= $nWordLen;        }        $sStrcut = substr($sString, 0, $nPos);    } else {        for ($i = 0; $i < $nLength; $i++) {            $sStrcut .= ord($sString[$i]) > 127 ? $sString[$i] . $sString[++ $i] : $sString[$i];        }    }        $sStrcut = str_replace(array("&", "\"", "<", ">"), array("&", "\"", "<", ">"), $sStrcut);    return $sStrcut . $sDot;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.