Re: Function Request: csv_explode()
| From: | Stig S. Bakken | Date: | Wed, 05 Dec 2001 08:29:05 +0000 |
| Subject: | Re: Function Request: csv_explode() | ||
| References: | 1 | Groups: | php.dev |
| Request: | Send a blank email to php-dev+get-72555@lists.php.net to get a copy of this message | ||
Splitting a CSV string into an array could be done like this too:
$fields = explode('","', trim($string, '"'));
- Stig
Justin Plock wrote:
>
> I guess this would be the correct list to post this on, but I have an idea
> for a function that I think would be very handy to users having to deal with
> CSV data. Basically, I've had to write a version of the explode() function,
> but have it pay attention to values that are wrapped in another character.
> For example:
>
> the delimiter is: ,
> and the wrapper is a: "
>
> the function would work as such:
>
> "this is some text","we can have a bunch of them","but, gotta, watch,
> out
> for those commas inside"
>
> it would return:
>
> "this is some text"
> "we can have a bunch of them"
> "but, gotta, watch, out for these commas inside"
>
> below is the PHP function I have developed:
>
> /**
> * Does an explode but pays attention to the delimeter.
> *
> * @param $splitter - string - required delimeter to split on
> * @param $wrap - string - required string to wrap text areas
> * @param $rest - string - required data to explode
> *
> * @return array - exploded array
> */
> function csv_explode($splitter, $wrap, $rest)
> {
> $instring = false;
> $field = '';
> $ret = array();
> while ($rest)
> {
> $first = substr($rest, 0, 1);
> $rest = substr($rest, 1);
> if ($first == $wrap)
> {
> $instring = (!$instring) ? true : false;
> }
> if (($first == $splitter) && !$instring)
> {
> $ret[] = $field;
> $field = '';
> }
> else
> {
> if ($first != $wrap)
> {
> $field .= $first;
> }
> }
> }
> $ret[] = $field;
> return($ret);
> }
>
> If I knew C, I would try to port this to a PHP myself, but I don't. I was
> just hoping someone else would. :)
>
> Thanks.
>
> -Justin Plock
>
> --
> PHP Development Mailing List <http://www.php.net/>
> To unsubscribe, e-mail: php-dev-unsubscribe@lists.php.net
> For additional commands, e-mail: php-dev-help@lists.php.net
> To contact the list administrators, e-mail: php-list-admin@lists.php.net