note 100264 deleted from function.str-getcsv by danbrown
| From: | danbrown@php.net | Date: | Tue, 05 Oct 2010 05:01:00 +0000 |
| Subject: | note 100264 deleted from function.str-getcsv by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-172962@lists.php.net to get a copy of this message | ||
Note Submitter: barry a cogan at googlemail dot com
----
The replacement function for previous versions, written by hpartidas at deuz dot net, did function
accurately for me. It can not seem to parse two commas with no space in between after handling an
enclosure. I was forced to write my own. This is what I came up with.
I hope you find it useful
<?php
if (!function_exists('str_getcsv'))
{
function str_getcsv($input, $delimiter = ',', $enclosure = '"', $escape =
'\\')
{
// Makes Sure we have correct input ELSE return false
if (is_string($input) && !empty($input))
{
$output = array(); // Initialize output array
$enclosures = explode($enclosure, $input); // Split line by double quote to exempt
"enclosed" delimiters
// Now we run through array and separate remaining delimiters
for($i=0; $i<count($enclosures); $i++)
{
// Even numbered array entries (0,2,4,...etc) become the areas outsite of the
"quotes".
if($i % 2 == 0)
{
// Make sure we dont allow a single delimiter to slip though as a segment.
if($enclosures[$i] != $delimiter)
{
// Remove any delimiters other than those at the beginning of $input string.
// These are delimiters which were used to separate our enclosures
if( (substr($enclosures[$i], 0, 1) == $delimiter) && ($i != 0 ) )
{
$enclosures[$i] = substr($enclosures[$i], 1);
}
// repeat this process for segment endings. Ignoring the last entry.
if( (substr($enclosures[$i], -1, 1) == $delimiter) && ($i != count($enclosures)-1) )
{
$enclosures[$i] = substr($enclosures[$i], 0, -1);
}
// Run a split on the cleaned segment to get the intended entries.
$lines = preg_split("/".$delimiter."/", $enclosures[$i]);
// Append each of thse entries to the output array.
foreach($lines as $line)
$output[] = $line;
}
}
else
{
// Odd numbered segments are our enclosed areas and are saved as is because we want to keep
these delimiters.
$output[] = $enclosures[$i];
}
}
// finally return our output.
return $output;
}
else
{
return false;
}
}
}
?>