explode() splits a string wherever the separator occurs and returns an array. The separator must not be an empty string.
$csv = 'red,green,blue';
$colors = explode(',', $csv);
print_r($colors);
$str="Welcome to plus2net php tutorial section";
$ar=explode(" ",$str);
print_r($ar);
We have used one space as delimiter. The output is here
Array ( [0] => Welcome [1] => to [2] => plus2net [3] => php [4] => tutorial [5] => section )
Here is its syntax
array explode(string $separator, string $string, int $limit = PHP_INT_MAX);
$str = "Welcome to plus2net php tutorial section";
$ar = explode(" ", $str, 3);
print_r($ar);
Output is here
Array ( [0] => Welcome [1] => to [2] => plus2net php tutorial section )
$str="my_userid@domain-name.com";
$ar=explode("@",$str);
print_r($ar);
We have used @ as delimiter in above code. Here is the output
Array ( [0] => my_userid [1] => domain-name.com )
Learn more on breaking email address here
https://www.plus2net.com/php_tutorial/string-explode.php
Now using explode function we will break the above url to separate domain part, directory and the file name.
$str="https://www.plus2net.com/php_tutorial/string-explode.php";
$my_array=explode("/",$str);
foreach ($my_array as $key => $val) {
echo "$key -> $val <br>";
}
The output is here
0 -> https:
1 ->
2 -> www.plus2net.com
3 -> php_tutorial
4 -> string-explode.php
To get a single output we can use like this
echo $my_array[2];
Output is
www.plus2net.com
$str="https://www.plus2net.com/php_tutorial/string-explode.php";
$my_array=explode("/",$str,3);
foreach ($my_array as $key => $val) {
echo "$key -> $val <br>";
}
Output is here
0 -> https:
1 ->
2 -> www.plus2net.com/php_tutorial/string-explode.php
With - negative value of limit
$str="https://www.plus2net.com/php_tutorial/string-explode.php";
$my_array=explode("/",$str,-2);
foreach ($my_array as $key => $val) {
echo "$key -> $val <br>";
}
Output is here
0 -> https:
1 ->
2 -> www.plus2net.com
For production URL parsing, use parse_url() rather than relying on fixed positions from explode().
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Manju | 18-03-2015 |
| this page is very helpful to me...I am really satisfied with these explanations.. and use of explode function ..I am very thankful. | |