支援中文的PHP按字串長度分割成數組代碼_php執行個體

來源:互聯網
上載者:User

以下是我編寫的代碼,實現對中英文混雜字元進行分割:

<?phpfunction mbStrSplit ($string, $len=1) {  $start = 0;  $strlen = mb_strlen($string);  while ($strlen) {    $array[] = mb_substr($string,$start,$len,"utf8");    $string = mb_substr($string, $len, $strlen,"utf8");    $strlen = mb_strlen($string);  }  return $array;}header('Content-type:text/html;charset=utf-8');$str = '我愛北京3我愛上海-我愛xianggang';$r = mbStrSplit($str, 4);echo '<pre>';print_r($r);echo '</pre>';?>

運行結果:

Array(  [0] => 我愛北京  [1] => 3我愛上  [2] => 海-我愛  [3] => xian  [4] => ggan  [5] => g)
<?php function str_split_unicode($str, $l = 0) { if ($l > 0) { $ret = array(); $len = mb_strlen($str,"UTF-8"); for ($i = 0; $i < $len; $i += $l) { $ret[] = mb_substr($str, $i, $l,"UTF-8");} return $ret;} return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);}?> $s ="還未如願sss見gfg者不rtret不朽"; // Mild milk print_r(str_split($s, 5)); print_r(str_split_unicode($s, 5));//輸出 //Array ( [0] => 還�� [1] => �如� [2] => ��sss [3] => 見gf [4] => g者� [5] => ��rtr [6] => et不 [7] => 朽 ) //Array ( [0] => 還未如願s [1] => ss見gf [2] => g者不rt [3] => ret不朽 )

以上所述就是本文的全部內容了,希望大家能夠喜歡。

相關文章

聯繫我們

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