Search code examples
phpstringexplode

PHP: How can I explode a string by commas, but not wheres the commas are within quotes?


I need to explode my string input into an array at the commas. However the string contains commas inside quotes.

Input:

$line = 'TRUE','59','A large number is 10,000';

$linearray = explode(",",$line);
$linemysql = implode("','",$linearray);

Returns $linemysql as:

'TRUE','59','A large number is 10','000'

How can I go about accomplishing this, with the explode ignoring the commas inside the quote marks?


Solution

  • Since you are using comma seperated values, you can use str_getcsv.

    str_getcsv($line, ",", "'");
    

    Will return:

    Array
    (
        [0] => TRUE
        [1] => 59
        [2] => A large number is 10,000
    )