Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to explode a variable in a little different way

Tags:

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?

like image 823
Ali Zia Avatar asked Oct 30 '15 05:10

Ali Zia


People also ask

What is array explode?

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?

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.


1 Answers

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" } 
like image 146
JPMC Avatar answered Sep 25 '22 03:09

JPMC