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: [EMAIL PROTECTED]
> For additional commands, e-mail: [EMAIL PROTECTED]
> To contact the list administrators, e-mail: [EMAIL PROTECTED]
--
PHP Development Mailing List <http://www.php.net/>
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
To contact the list administrators, e-mail: [EMAIL PROTECTED]