Re: Conditional explode?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Thu, 1 Jul 2004 15:09:38 -0500, Matt M. <h.dudeness@xxxxxxxxx> wrote:
> 
> On Thu, 1 Jul 2004 14:05:49 -0500, Shiloh Madsen
> <shiloh_madsen@xxxxxxxxxxxxxxx> wrote:
> >
> > Can I use explode in a conditional manner? I.E., can i have it explode on a space, but only if the space is not encased in double quotes?
> 
> I would use http://www.php.net/preg_split
> 

I'm not sure how you could do that as there could be multiple sets of
quotes. If you have:

1 2 "3 4" 5 6 "7 8" 9

How would you write a preg to split only on those *not* encased in quotes?

Here was my solution (posted before for another question):

/**
 * does a regular explode, 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 explode by
 * @param string text to explode
 * @param string text which surrounds quoted fields (defaults to ")
 * @return array array of fields after explode
 */
function explodeQuoteFriendly($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;
}

-- 
DB_DataObject_FormBuilder - The database at your fingertips
http://pear.php.net/package/DB_DataObject_FormBuilder

paperCrane --Justin Patrin--

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


[Index of Archives]     [PHP Home]     [PHP Users]     [Postgresql Discussion]     [Kernel Newbies]     [Postgresql]     [Yosemite News]

  Powered by Linux