Thanks Justin. Works like a charm

vp

On Wed, 23 Jun 2004 08:48:57 -0700, Justin Patrin
<[EMAIL PROTECTED]> wrote:
> 
> 
> 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>
> 
> 
> 
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
> 
>

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to