In PHP, the str_split() function is a very practical tool that can split a string into an array of single characters. This function is especially useful when strings need to be processed by character characters. Next, we will introduce the basic usage of the str_split() function and parse its functions with some examples.
The str_split() function splits strings into single characters and stores them in an array. The function prototype is as follows:
array str_split(string $string, int $length = 1)
$string : This is the original string that needs to be split.
$length : This is the length of each split substring. The default is 1, which means that each character will be stored in the array as an element.
This function returns an array where each element is a character extracted from the original string. If the $length parameter is provided, it is split by the specified length.
<?php
$string = "Hello, world!";
$array = str_split($string);
print_r($array);
?>
Array
(
[0] => H
[1] => e
[2] => l
[3] => l
[4] => o
[5] => ,
[6] =>
[7] => w
[8] => o
[9] => r
[10] => l
[11] => d
[12] => !
)
In this example, we split the string "Hello, world!" into an array of each character.
<?php
$string = "Hello, world!";
$array = str_split($string, 5);
print_r($array);
?>
Array
(
[0] => Hello
[1] => , wor
[2] => ld!
)
In this example, str_split() splits the string into three parts according to length 5, and the result is an array containing substrings.
Suppose we have a string containing the URL and we need to split the string into a character array. Assuming that the domain name of the URL is m66.net , we can use str_split() to split the string and process it: