Search code examples
phpstringcsvdelimiterexplode

Explode string to elements


I need to explode() this

'194', '??','Dot, is', "3","0", '4', '35',, 0, 'ANIMAL','STUN,SLOW,CURSE,TERROR'

into separated elements.

The content of elements may be in quotation marks or apostrophe (but may not be quoted at all).

Zero-width strings need to be matched as well.

As you can see, I cannot explode it by comma, because commas are included in some elements.

Somewhere there are spaces missing between elements and spaces may be included in element itself.

Result should be:

Element 0 = 194
Element 1 = ??
Element 2 = Dot, is
Element 3 = 3
Element 4 = 0
Element 5 = 4
Element 6 = 35
Element 7 =
Element 8 = 0
Element 9 = ANIMAL
Element 10 = STUN,SLOW,CURSE,TERROR


Solution

  • Use str_replace() to convert ' to "; then use str_getcsv()

    $str = "'194', '??','Dot, is', \"3\",\"0\", '4', '35',, 0, 'ANIMAL','STUN,SLOW,CURSE,TERROR'";
    
    $array = str_getcsv(
        str_replace("'", '"', $str)
    );
    
    var_dump($array);