Home >Backend Development >PHP Tutorial >PHP specifies the length to split the string str_split function usage example

PHP specifies the length to split the string str_split function usage example

高洛峰
高洛峰Original
2017-02-03 15:20:191723browse

The example in this article describes the usage of str_split function in PHP to split strings with specified length. Share it with everyone for your reference, the details are as follows:

Example 1:

$str = 'abcdefgh';
$arr = str_split($str,2);

The running results are as follows:

array(4) {
 [0]=>
 string(2) "ab"
 [1]=>
 string(2) "cd"
 [2]=>
 string(2) "ef"
 [3]=>
 string(2) "gh"
}

Example 2:

$str = 'abcdefgh';
$arr = str_split($str);
$i = 0;
$limit = 3;
$num = count($arr);
while($i <= $num-1){
  $temp = array();
  $for_countbu = ($num-$i) >= $limit ? $limit : $num - $i;
  for($j = 0; $j < $for_countbu; ++$j)
  {
    $temp[] = $arr[$i];
    ++$i;
  }
  $one = implode(&#39;&#39;,$temp);
  $result[] = $one;
}
print_r($result);

The running results are as follows:

array(4) {
 [0]=>
 string(2) "ab"
 [1]=>
 string(2) "cd"
 [2]=>
 string(2) "ef"
 [3]=>
 string(2) "gh"
}

I hope this article will be helpful to everyone in PHP programming. .

For more PHP specified length split string str_split function usage examples, please pay attention to the PHP Chinese website!

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