Assuming you have a string as follows:
$str = 'one value, two value, "three, cool value", four value';
How would you make it a开发者_开发百科n 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.)
If you are really parsing it from a string, use str_getcsv.
If you are reading data from a file, use fgetcsv.
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"
}
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.
str_getcsv() use this function with enclosure as '\"'
.
It looks like this: $csv = str_getcsv($csvstring,',','\"');
Using str_getcsv
together with array_map
and trim
does precisely this. You use str_getcsv
to break the items into an array, and then array_map
and trim
to trim off the whitespace from each item.
PHP → JSON Format
WITHOUT TRIM
echo json_encode(str_getcsv('one value, two value, "three, cool value", four value'));
This produces:
// some array items include extra whitespace without `trim()`
["one value"," two value","three, cool value"," four value"]
WITH TRIM
echo json_encode(array_map('trim', str_getcsv('one value, two value, "three, cool value", four value')));
This produces:
["one value","two value","three, cool value","four value"]
PHP Format
To use the final result in JSON format, use echo json_encode(…)
as I did above. Otherwise, if you would like to continue using this as a PHP array, then use var_dump(…)
without json_encode. You can do it like here (including trim()
):
var_dump(array_map('trim', str_getcsv('one value, two value, "three, cool value", four value')));
This produces:
array(4) {
[0]=>
string(9) "one value"
[1]=>
string(9) "two value"
[2]=>
string(17) "three, cool value"
[3]=>
string(10) "four value"
}
This is correct PHP format, the PHP equivalent of:
["one value","two value","three, cool value","four value"]
You could look around at fgetcsv.
There are two ways.
If you're going to quote entries, quote every entries. Then explode the string with "," (with quotes).
Replace commas with something uncommon before parsing. Like {|}
精彩评论