I have a string that need to be split out :
3,1,'2015,05,14,11,18,0', 99
I want to split it into
3
1
'2015,05,14,11,18,0'
99
How could I do this with PHP ?
I have a string that need to be split out :
3,1,'2015,05,14,11,18,0', 99
I want to split it into
3
1
'2015,05,14,11,18,0'
99
How could I do this with PHP ?
One of the comments (@tuananh in particular) said csv parser
, so a little bit of trial, fgetcsv
will work too, you'll just got to have that temporary file that holds the simple string, just unlink it after the operation.
Just set the enclosure to single quotes so that when the parser breaks it up, it gets the whole string enclosed with single quotes.
$string = "3,1,'2015,05,14,11,18,0', 99";
file_put_contents('temp.csv', $string); // create temporary file
$fh = fopen('temp.csv', 'r'); // open
$line = fgetcsv($fh, strlen($string) + 1, ',', "'"); // set enclosure to single quotes
fclose($fh);
unlink('temp.csv'); // remove temp file
print_r($line); // Array ( [0] => 3 [1] => 1 [2] => 2015,05,14,11,18,0 [3] => 99 )
// echo implode("\n", $line);
Sidenote: If this is indeed a csv file, then just use fgetcsv
for the whole thing.
EDIT: As @deceze said about use the csv function for strings
There's this thing called str_getcsv
, so no need to actually put it inside a file the unlink it whatsoever.
$string = "3,1,'2015,05,14,11,18,0', 99";
$line = str_getcsv($string, ',', "'"); // set enclosure to single quotes
print_r($line);