Home > Article > Backend Development > How to split string into array php
In PHP, splitting a string into an array usually uses the built-in function explode()
. This function can split a string into an array according to the specified delimiter.
The following is the syntax of the explode()
function:
explode(separator, string, limit);
Among them, separator
is the specified separator, at which the character is Split the string and generate array elements; string
is the string to be split; limit
is optional and is used to limit the maximum number of returned array elements.
Below we use an example to illustrate how to use the explode()
function to split a string into an array.
Suppose we have the following string:
$str = "Hello world, I am here!";
We want to split it into an array of words. At this point, we can use the space character as a separator to split it into individual words. The sample code is as follows:
$str = "Hello world, I am here!"; $words = explode(" ", $str); print_r($words);
The output of the above code is:
Array ( [0] => Hello [1] => world, [2] => I [3] => am [4] => here! )
As you can see, we successfully split the string into an array containing each word.
Now, let’s say we have a comma separated string:
$str = "apple,banana,orange";
We want to split it into an array of fruits. At this point, we can use commas as separators. The sample code is as follows:
$str = "apple,banana,orange"; $fruits = explode(",", $str); print_r($fruits);
The output of the above code is:
Array ( [0] => apple [1] => banana [2] => orange )
As you can see, we successfully split the string into a fruit array.
Suppose we have a string of 4 digits stored bit by bit as follows:
$str = "1-2-3-4";
Now we want to Split into an array so that the output result is an integer array [1,2,3,4]
. At this time, we can use the connector -
as the separator, and use the limit
parameter to limit the array to only contain 4 elements. The sample code is as follows:
$str = "1-2-3-4"; $numbers = explode("-", $str, 4); print_r($numbers);
The output of the above code is:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
As you can see, we successfully split the string into an integer array.
Summary:
In PHP, we can use the explode()
function to split a string into an array according to the specified delimiter. The syntax format of this function is explode(separator, string, limit)
, where separator
is the separator, string
is the string to be split, limit
is used to limit the number of elements in the array.
The above is an example of how to split a string into an array. I hope it will be helpful to you.
The above is the detailed content of How to split string into array php. For more information, please follow other related articles on the PHP Chinese website!