Search code examples
phpcsvsplit

Split a CSV string only containing single-quoted values into a two-element array


I have a string that looks like this:

'word','another word','and a sentence','and more','etc etc'

I need to split this into two strings, divided by the second comma -- which shouldn't show in either of the sentences. What complicates things is that here can also be commas inside the various quotes parts of the string.


Solution

  • $a="'word','another word','and a sentence','and more','etc etc'";
    
    //preg_match('{(.*?,[^,]*),(.*)}', $a, $matches);
    preg_match('{(.*?[^\\\\]\',.*?[^\\\\]\'),(.*)}', $a, $matches); //UPDATE 
    print_r($matches);
    

    DISPLAY:

        Array
    (
        [0] => 'word','another word','and a sentence','and more','etc etc'
        [1] => 'word','another word'
        [2] => 'and a sentence','and more','etc etc'
    )