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 ?

4
  • Is this what you are looking for? stackoverflow.com/questions/11456850/… You would just need to replace the " with ' Commented May 14, 2015 at 4:17
  • 1
    Did you try something or are you waiting us to write the code ... ? Commented May 14, 2015 at 4:17
  • I tried with explode the "," but it doesn't work because of '2015,05,14,11,18,0' Commented May 14, 2015 at 4:19
  • 1
    Hint: Use csv parser Commented May 14, 2015 at 4:20

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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 lol :D there is that str_getcsv i forgot about it, thanks for the reminder

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.