explode()We can break a string and create an array out of it by using a delimiter. Here is its syntax
array explode( delimiter, string-to-break, limit);
We can specify the delimiter and 2nd parameter is the string we want to break and third parameter is optional by which we can fix the number of elements of the array. Let us try some examples. We have used print_r function to display the elements of the array we get out of our explode function.
$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 )
We don't want more than three elements to in the array then change the code like this.
$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 )
Breaking an email address using explode
We can use explode function to separate userid part and domain part from an email address . Let us try this example.
$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
|