Search code examples
phpcsvtext-extractiontext-parsing

Parse a single-line csv string containing double-quoted values


I have a string like:

$string = '"lorem ipsum","dolor, sit","amet"';

I am trying to use EXPLODE and preg_match in order to get each of the elements within " .. " as a string on its own, rendering the original string into an array.

Which would give me in the end;

$array[0] = 'lorem ipsum';
$array[1] = 'dolor, sit';
$array[2] = 'amet';

Some strings-to-be contain comma inbetween so my attempts of trying explode to separate them and then replacing or preg_matching to extract in between " .. " fails.

How can I achieve the desired goal?

Thank you.


Solution

  • You should replace your combination of functions with a function that is made specifically for this: str_getcsv:

    $array = str_getcsv($string, ',', '"');
    

    (options added for clarity)