萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> 支持中文的PHP按字符串長度分割成數組代碼

支持中文的PHP按字符串長度分割成數組代碼

   自己編寫的PHP按字符串長度分割成數組代碼,支持中文字符,下面給出代碼和使用方法,有需要的小伙伴可以參考下。

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

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <?php function 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>'; ?>

  運行結果:

  ?

1 2 3 4 5 6 7 8 9 Array ( [0] => 我愛北京 [1] => 3我愛上 [2] => 海-我愛 [3] => xian [4] => ggan [5] => g )

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 <?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不朽 )

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

copyright © 萬盛學電腦網 all rights reserved