PHP實現mb_substr函數

來源:互聯網
上載者:User
 1 <?php 2     function myMbSubstr($str, $start, $length, $charset){ 3         $charsets["utf-8"] = $charsets["utf8"] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/"; 4         $charsets["gb2312"] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/"; 5         $charsets["gbk"] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/"; 6         $charsets["big5"] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/"; 7          8         preg_match_all($charsets[$charset], $str, $matches);    #按照指定編碼將字串切分成一個數組 9         10         #var_dump($matches);11         12         $substr = implode("", array_slice($matches[0], $start, $length));    #擷取數組的子數組,並將子數組的元素串連起來13         14         return $substr;15     }16     17     $str = "I'm a 碼農";18     19     echo "<br>" . myMbSubstr($str, 0, 7, "utf8") . "<br>";20     echo mb_substr($str, 0, 7, "utf8");21 ?>

輸出

array(1) { [0]=> array(8) { [0]=> string(1) "I" [1]=> string(1) "'" [2]=> string(1) "m" [3]=> string(1) " " [4]=> string(1) "a" [5]=> string(1) " " [6]=> string(3) "碼" [7]=> string(3) "農" } } 
I'm a 碼
I'm a 碼

相關文章

聯繫我們

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