Home  >  Article  >  Backend Development  >  PHP that supports Chinese is divided into array codes according to the length of the string, _PHP tutorial

PHP that supports Chinese is divided into array codes according to the length of the string, _PHP tutorial

WBOY
WBOYOriginal
2016-07-13 09:53:32860browse

Support Chinese PHP to split into array codes according to string length,

The following is the code I wrote to split Chinese and English mixed characters:

<&#63;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 class="brush:php;toolbar:false">';
print_r($r);
echo '
'; ?>

Run result:

Array
(
  [0] => 我爱北京
  [1] => 3我爱上
  [2] => 海-我爱
  [3] => xian
  [4] => ggan
  [5] => g
)

<&#63;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);
}
&#63;>
 $s ="还未如愿sss见gfg者不rtret不朽"; // Mild milk
 print_r(str_split($s, 5));
 print_r(str_split_unicode($s, 5));

//输出
 //Array ( [0] => 还&#65533;&#65533; [1] => &#65533;如&#65533; [2] => &#65533;&#65533;sss [3] => 见gf [4] => g者&#65533; [5] => &#65533;&#65533;rtr [6] => et不 [7] => 朽 )
 //Array ( [0] => 还未如愿s [1] => ss见gf [2] => g者不rt [3] => ret不朽 )

The above is the entire content of this article, I hope you all like it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1000258.htmlTechArticleSupport Chinese PHP to split into array codes according to string length. The following is the code I wrote to implement Chinese and English Split mixed characters: phpfunction mbStrSplit ($string, $len=1) {...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn