I have this variable.
$var = "A,B,C,D,'1,2,3,4,5,6',E,F";
I want to explode it so that I get the following array.
array( [0] => A, [1] => B, [2] => C, [3] => D, [4] => 1,2,3,4,5,6, [5] => E, [6] => F );
I used explode(',',$var)
but I am not getting my desired output. Any suggestions?
The explode() function splits a string based on a string delimiter, i.e. it splits the string wherever the delimiter character occurs. This functions returns an array containing the strings formed by splitting the original string. Syntax : array explode(separator, OriginalString, NoOfElements)
What Is Explode in PHP. A built-in function in PHP that splits a string into different strings is known as explode(). The splitting of the string is based on a string delimiter, that is, explode in PHP function splits the string wherever the delimiter element occurs.
There is an existing function that can parse your comma-separated string. The function is str_getcsv
It's signature is like so:
array str_getcsv ( string $input [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]] )
Your only change would be to change the 3rd variable, the enclosure, to single quotes rather than the default double quotes.
Here is a sample.
$var = "A,B,C,D,'1,2,3,4,5,6',E,F"; $array = str_getcsv($var,',',"'");
If you var_dump
the array, you'll get the format you wanted:
array(7) { [0]=> string(1) "A" [1]=> string(1) "B" [2]=> string(1) "C" [3]=> string(1) "D" [4]=> string(11) "1,2,3,4,5,6" [5]=> string(1) "E" [6]=> string(1) "F" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With