Splitting a string is needed whenever you wish to take a specific part of the string after a specific character. Suppose I have string (“Hello: Hunny I just make you call, cell was out or range”), I want to pick this specific part of the string after the sign(:). Better way is to use explode here to save time and split string into string.
1 |
$originalString = “Hello: Hunny I just make you call, cell was out of range”; $returnString = explode(‘:’,$originalString);
|
Output: Array ( [0] => Hello [1] => Hunny I just make you call, cell was out of range ) I have second example here, Suppose I have a list of names separated with spaces, I want to separate all the names using explode().
1 2 3 4 5 |
$names = "Rizwan Mudasir Salman Azam Nauman Hassan Awais";
$split = explode(" ",$names); echo $split[0]; echo '<br />'; echo $split[3]; echo '<br />'; echo $split[4]; echo '<br />';
echo $split[5];
|
This was with the array. Let us play with Lists. I have here a simple example of list using explode().
1 2 3 4 5 6 7 8 9 10 11 |
echo '<hr /><h3>Lets Play with Lists</h3>';
$originalList = "mudasir:123:Engineer:ComputerSneaker";
list($name,$pass,$pro,$website)= explode(":",$originalList);
echo '<br/>'.$name; echo '<br/>'.$pass;
echo '<br/>'.$pro;
echo '<br/>'.$website;
|
And my last example is for limit parameters. Let’s have a look at the followi9ng example.
1 2 3 4 5 |
echo '<hr /><h3>Using Limit Parameters</h3>';
$originalString = "Name|Pass|Profession|Web";
$newString = explode("|",$originalString,1); print_r($newString);
|
In the end I have complete code here that I have used, You can make necessary changes into it and can use this code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
$originalString = "Hello: Hunny I just make you call, cell was out of range";
$returnString = explode(':',$originalString); print_r($returnString); echo '<hr />';
$names = "Rizwan Mudasir Salman Azam Nauman Hassan Awais";
$split = explode(" ",$names);
echo $split[0]; echo '<br />';
echo $split[3]; echo '<br />';
echo $split[4];echo '<br />';
echo $split[5];
echo '<hr /><h3>Lets Play with Lists</h3>';
$originalList = "mudasir:123:Engineer:ComputerSneaker";
list($name,$pass,$pro,$website)= explode(":",$originalList); echo '<br/>'.$name;
echo '<br/>'.$pass; echo '<br/>'.$pro; echo '<br/>'.$website;
echo '<hr /><h3>Using Limit Parameters</h3>';
$originalString = "Name|Pass|Profession|Web";
$newString = explode("|",$originalString,1); print_r($newString);
|
Here is the output of above code.
Random Posts






