PHP 中文字串截取方法匯總

來源:互聯網
上載者:User

PHP 截取字串代碼

通過指定編碼進行字串截取:

12345678910111213141516171819202122232425
/** * @todo 中文截取,支援gb2312,gbk,utf-8,big5 * * @param string $str 要截取的字串 * @param int $start 截取起始位置 * @param int $length 截取長度 * @param string $charset utf-8|gb2312|gbk|big5 編碼 * @param $suffix 是否加尾綴 */function CsubStrPro($str, $start = 0, $length, $charset = "utf-8", $suffix = true){    if (function_exists ( "mb_substr" ))        return mb_substr ( $str, $start, $length, $charset );     $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 ) );    if ($suffix)        return $slice . "…";     return $slice;}

2:自動識別 GBK 和UTF-8 編碼的字串

1234567891011121314151617181920212223242526272829303132333435363738
function cutStr($sourcestr, $cutstart=0, $cutlength) {    $returnstr = '';    $i = 0;    $n = 0;    $str_length = strlen ( $sourcestr ); //字串的位元組數    while ( ($n < $cutlength) and ($i <= $str_length) ) {        $temp_str = substr ( $sourcestr, $i, 1 );        $ascnum = Ord ( $temp_str ); //得到字串中第$i位字元的ascii碼        if ($ascnum >= 224) //如果ASCII位高與224,        {            $returnstr = $returnstr . substr ( $sourcestr, $i, 3 ); //根據UTF-8編碼規範,將3個連續的字元計為單個字元            $i = $i + 3; //實際Byte計為3            $n ++; //字串長度計1        }        elseif ($ascnum >= 192) //如果ASCII位高與192,        {            $returnstr = $returnstr . substr ( $sourcestr, $i, 2 ); //根據UTF-8編碼規範,將2個連續的字元計為單個字元            $i = $i + 2; //實際Byte計為2            $n ++; //字串長度計1        }        elseif ($ascnum >= 65 && $ascnum <= 90) //如果是大寫字母,        {            $returnstr = $returnstr . substr ( $sourcestr, $i, 1 );            $i = $i + 1; //實際的Byte數仍計1個            $n ++; //但考慮整體美觀,大寫字母計成一個高位字元        }        else //其他情況下,包括小寫字母和半形標點符號,        {            $returnstr = $returnstr . substr ( $sourcestr, $i, 1 );            $i = $i + 1; //實際的Byte數計1個            $n = $n + 0.5; //小寫字母和半形標點等與半個高位字元寬...        }    }    if ($str_length > $i) {        $returnstr = $returnstr . "..."; //超過長度時在尾處加上省略符號    }    return $returnstr;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.