3

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 ?

Dao Quoc Khanh
  • 613
  • 1
  • 7
  • 13

1 Answers1

2

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);
Kevin
  • 41,694
  • 12
  • 53
  • 70
  • 1
    You could use an in-memory buffer instead of a physical file; or use the csv function for strings. This is needlessly complicated either way. – deceze May 14 '15 at 05:43
  • @deceze lol :D there is that `str_getcsv` i forgot about it, thanks for the reminder – Kevin May 14 '15 at 05:48