Split
, explodeIn PHP the explode()
function is used for splitting strings on a delimiter. It takes the parts of a string
and separates them into an array.
With a delimiter, we specify where the separations occur. Usually we separate based on a character like a comma or newline. We can loop over the resulting array with foreach
.
To begin we specify an input string
that contains 3 words, and 2 commas separating the words. This is the string
we want to split apart.
explode()
with two arguments—the first is the delimiter character. In this example, the comma is our delimiter.string
we want to split apart as the second argument to explode()
.$value = "one,two,three"; // Separate string based on comma. $result = explode(",", $value); // Loop over result and print elements. foreach ($result as $r) { print($r . "\n"); }one two three
It is possible to specify the maximum array size we want to receive from explode. We specify a limit argument as the third parameter to explode.
$value = "a,b,c,d"; // Split into two elements. $result = explode(",", $value, 2); var_dump($result);array(2) { [0]=> string(1) "a" [1]=> string(5) "b,c,d" }
In PHP the "split" and "join" functions are called explode and implode, and with them we can round-trip our data. We can get the original string
back after splitting it apart.
$value = "blue,red,green"; var_dump($value); // Explode the string, and then implode it to get the original back. $result = explode(",", $value); $value = implode(",", $result); var_dump($value);string(14) "blue,red,green" string(14) "blue,red,green"
Str_split
There is a string
split function in PHP, but it works to separate a string
into fixed-sized chunks of a certain length. It does not act upon delimiters.
string
we want to separate into chunks as the first argument to str_split
.string
element) is the second argument.$value = "aaaaaaa"; // Use split to get "chunks" from the string. // Split in PHP does not use delimiters. $result = str_split($value, 3); var_dump($result);array(3) { [0]=> string(3) "aaa" [1]=> string(3) "aaa" [2]=> string(1) "a" }
By exploding and imploding strings, we convert strings to arrays and back to strings in PHP. These functions are named in an unusual way, but they perform standard split and join operations.