支持中文的PHP按字符串长度分割成数组代码

自己编写的PHP按字符串长度分割成数组代码,支持中文字符,下面给出代码和使用方法,有需要的小伙伴可以参考下。

以下是我编写的代码,实现对中英文混杂字符进行分割:

  1. <?php
  2. function mbStrSplit ($string, $len=1) {
  3. $start = 0;
  4. $strlen = mb_strlen($string);
  5. while ($strlen) {
  6. $array[] = mb_substr($string,$start,$len,"utf8");
  7. $string = mb_substr($string, $len, $strlen,"utf8");
  8. $strlen = mb_strlen($string);
  9. }
  10. return $array;
  11. }
  12. header('Content-type:text/html;charset=utf-8');
  13. $str = '我爱北京3我爱上海-我爱xianggang';
  14. $r = mbStrSplit($str, 4);
  15. echo '<pre>';
  16. print_r($r);
  17. echo '</pre>';
  18. ?>

运行结果:

  1. Array
  2. (
  3. [0] => 我爱北京
  4. [1] => 3我爱上
  5. [2] => 海-我爱
  6. [3] => xian
  7. [4] => ggan
  8. [5] => g
  9. )
  10. <?php
  11. function str_split_unicode($str, $l = 0) {
  12. if ($l > 0) {
  13. $ret = array();
  14. $len = mb_strlen($str,"UTF-8");
  15. for ($i = 0; $i < $len; $i += $l) {
  16. $ret[] = mb_substr($str, $i, $l,"UTF-8");
  17. }
  18. return $ret;
  19. }
  20. return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
  21. }
  22. ?>
  23. $s ="还未如愿sss见gfg者不rtret不朽"; // Mild milk
  24. print_r(str_split($s, 5));
  25. print_r(str_split_unicode($s, 5));
  26. //输出
  27. //Array ( [0] => 还�� [1] => �如� [2] => ��sss [3] => 见gf [4] => g者� [5] => ��rtr [6] => et不 [7] => 朽 )
  28. //Array ( [0] => 还未如愿s [1] => ss见gf [2] => g者不rt [3] => ret不朽 )

以上所述就是本文的全部内容了,希望大家能够喜欢。