tags:

views:

88

answers:

5

Assuming you have a string as follows:

$str = 'one value, two value, "three, cool value", four value';

How would you make it an array as follows:

$arr = array('one value', 'two value', 'three, cool value', 'four value');

(That's all about CSV and values that contain a comma and thus are double quoted.)

+1  A: 

You could look around at fgetcsv.

fabrik
+6  A: 

If you are really parsing it from a string, use str_getcsv.

If you are reading data from a file, use fgetcsv.

jasonbar
Note that if you're using PHP < 5.3, and you need to read it from a string, you can use the 'var' stream wrapper. See http://codepad.org/XepyeDSd
TML
+2  A: 

Assuming you're using 5.3.0 or newer, use str_getcsv. If you're using an older version of PHP, try fgetcsv with the 'var' stream wrapper from here. An example of the last can be found at this codepad.

TML
+5  A: 

You can use str_getcsv

$str = 'one value, two value, "three, cool value", four value';
var_dump(str_getcsv($str));                                     

Results:

array(4) {
  [0]=>
  string(9) "one value"
  [1]=>
  string(9) "two value"
  [2]=>
  string(17) "three, cool value"
  [3]=>
  string(10) "four value"
}
codaddict
A: 

There are two ways.

  1. If you're going to quote entries, quote every entries. Then explode the string with "," (with quotes).

  2. Replace commas with something uncommon before parsing. Like {|}

Moe Sweet
No need to do that, actually - both fgetcsv() and str_getcsv() handle the quoting style demonstrated just fine.
TML