Re: CSV explode problem
| From: | Matt Matijevich | Date: | Wed, 23 Jun 2004 15:37:13 +0000 |
| Subject: | Re: CSV explode problem | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-188885@lists.php.net to get a copy of this message | ||
[snip]
Any help with parsing a string to replace those comma in string?
[/snip]
this was in the user comments on
http://www.php.net/manual/en/function.fgetcsv.php
function csv_split($line,$delim=',',$removeQuotes=true) {
#$line: the csv line to be split
#$delim: the delimiter to split by
#$removeQuotes: if this is false, the quotation marks won't be removed
from the fields
$fields = array();
$fldCount = 0;
$inQuotes = false;
for ($i = 0; $i < strlen($line); $i++) {
if (!isset($fields[$fldCount])) $fields[$fldCount] = "";
$tmp = substr($line,$i,strlen($delim));
if ($tmp === $delim && !$inQuotes) {
$fldCount++;
$i += strlen($delim)-1;
} else if ($fields[$fldCount] == "" && $line[$i] == '"'
&&
!$inQuotes) {
if (!$removeQuotes) $fields[$fldCount] .= $line[$i];
$inQuotes = true;
} else if ($line[$i] == '"') {
if ($line[$i+1] == '"') {
$i++;
$fields[$fldCount] .= $line[$i];
} else {
if (!$removeQuotes) $fields[$fldCount] .= $line[$i];
$inQuotes = false;
}
} else {
$fields[$fldCount] .= $line[$i];
}
}
return $fields;
}
$line = '1,2,3,"this string gets parsed , at the comma"';
print_r(csv_split($line));