note 51802 deleted from function.explode by bjori
| From: | bjori@php.net | Date: | Mon, 25 Sep 2006 08:10:14 +0000 |
| Subject: | note 51802 deleted from function.explode by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-117592@lists.php.net to get a copy of this message | ||
Note Submitter: richardkmiller at gmail dot com
----
The function posted by tengel at fluid dot com didn't work for me -- it wouldn't compile.
Here is the function I wrote to do the same thing. This function explodes a string, ignoring
delimeters that appear inside double quotes. (Incidentally, it also removes double quotes from the
exploded elements.)
This correctly parses, for example, a line from a CSV file like this:
10, "abc", "ACME, Inc.", 50.25
It's slow, but it works. (How could this be faster?)
function explode2($delimeter, $string)
{
for ($i = 0; $i < strlen($string); $i++)
{
if ($string{$i} == '"')
{
if ($insidequotes)
$insidequotes = false;
else
$insidequotes = true;
}
elseif ($string{$i} == $delimeter)
{
if ($insidequotes)
{
$currentelement .= $string{$i};
}
else
{
$returnarray[$elementcount++] = $currentelement;
$currentelement = '';
}
}
else
{
$currentelement .= $string{$i};
}
}
$returnarray[$elementcount++] = $currentelement;
return $returnarray;
}