Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 485
Nicekiwi Avatar asked Feb 27 '11 10:02

Nicekiwi


People also ask

How can use comma separated string in PHP?

The task is to split the given string with comma delimiter and store the result in an array. Use explode() or preg_split() function to split the string in php with given delimiter. PHP | explode() Function: The explode() function is an inbuilt function in PHP which is used to split a string in different strings.

How do you separate an array with a comma?

The comma separated list can be created by using implode() function. The implode() is a builtin function in PHP and is used to join the elements of an array. implode() is an alias for PHP | join() function and works exactly same as that of join() function.


1 Answers

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 ) 
like image 64
Russell Dias Avatar answered Sep 28 '22 23:09

Russell Dias