Re: CSV explode problem

From: Date: Wed, 23 Jun 2004 15:48:57 +0000
Subject: Re: CSV explode problem
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-188886@lists.php.net to get a copy of this message
V Patel wrote:
I have a csv string. But the string also contains other strings with commas. Explode is not working with this kind of string. For example, 1,2,3,"this string gets parsed , at the comma" Result of explode(",",string) is 1 2 3 this string gets parsed at the comma But what I want is 1 2 3 this string gets parsed , at the comma I am not fluent with regular expressions. If anybody could help. Thanks, Vp
Here's a funciton I cooked up to deal with this: <?php /** * does a regular split, but also accounts for the deliminator to be within quoted fields * for example, if called as such: * splitQuoteFriendly(',', '0,1,2,"3,I am still 3",4'); * it will return: * array(0 => '0',
 *         1 => '1',
 *         2 => '2',
 *         3 => '"3,I am still 3"',
 *         4 => '4');
* @param string deliminator to split by * @param string text to split * @param string text which surrounds quoted fields (defaults to ") * @return array array of fields after split */ function splitQuoteFriendly($delim, $text, $quote = '"') { $strictFields = explode($delim, $text); for($sl = 0, $l = 0; $sl < sizeof($strictFields); ++$sl) {
    $fields[$l] = $strictFields[$sl];
    $numQuotes = 0;
    while(fmod($numQuotes += substr_count($strictFields[$sl], $quote), 2) == 1) {
      ++$sl;
      $fields[$l] .= $delim.$strictFields[$sl];
    }
    ++$l;
} return $fields; } ?> Just do a splitQuoteFriendly("\n", $csv), then loop through the resulting array and do splitQuoteFriendly(',', $line). -- paperCrane <Justin Patrin>

« previous php.general (#188886) next »