PHP Split string with exception

I have a string that needs to be split:

3,1,'2015,05,14,11,18,0', 99

      

I want to break it down into

3
1
'2015,05,14,11,18,0'
99

      

How can I do this from PHP?

+3


source to share


1 answer


One of the comments (specifically @tuananh) said csv parser

so a little trial fgetcsv

will work too, you just get this temp file which contains a simple string, just unlink after the operation.

Just set the shell to single quotes so that when you break the parse, it will get the entire string enclosed in 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 it really is a csv file, just use fgetcsv

for everything.



EDIT: As @deceze said about using the csv function for strings

There the thing is called str_getcsv

, so there is no need to actually put it inside a file to undo it altogether.

$string = "3,1,'2015,05,14,11,18,0', 99";
$line = str_getcsv($string, ',', "'"); // set enclosure to single quotes
print_r($line);

      

+2


source







All Articles