note 28780 modified in function.explode by aidan
| From: | aidan@php.net | Date: | Sun, 27 Jun 2004 14:29:13 +0000 |
| Subject: | note 28780 modified in function.explode by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-71930@lists.php.net to get a copy of this message | ||
I've run across certain CSV (comma delimited) files that do not follow the standard "quote
the sections that have commas as part of the string" formatting. Instead, these files escape
the commas that are part of the field with a backslash.
Here's some code to explode a CSV string formatted in such a way into an array:
<?php
function csv_explode($expldchar, $str)
{
if (strlen($expldchar) != 1 || strlen($str) == 0) {
return 0;
}
$idx=0;
$arr=0;
while($idx < strlen($str))
{
if($str[$idx] == '\\')
{
$idx+=2;
$newstrarr[$arr] = $newstrarr[$arr] . $str[$idx];
}
elseif($str[$idx] == ',') $arr++;
else $newstrarr[$arr] = $newstrarr[$arr] . $str[$idx];
$idx++;
}
return $newstrarr;
}
?>
(Disclaimer: I'm not a professional programmer and, more than likely, improvements and
efficiencies can be made to the code segment above.)
--was--
I've run across certain CSV (comma delimited) files that do not follow the standard "quote
the sections that have commas as part of the string" formatting. Instead, these files escape
the commas that are part of the field with a backslash.
Here's some code to explode a CSV string formatted in such a way into an array:
function csv_explode($expldchar, $str)
{
if(strlen($expldchar) != 1 || strlen($str) == 0)
{
return 0;
}
$idx=0;
$arr=0;
while($idx < strlen($str))
{
if($str[$idx] == '\\')
{
$idx+=2;
$newstrarr[$arr] = $newstrarr[$arr] . $str[$idx];
}
elseif($str[$idx] == ',') $arr++;
else $newstrarr[$arr] = $newstrarr[$arr] . $str[$idx];
$idx++;
}
return $newstrarr;
}
(Disclaimer: I'm not a professional programmer and, more than likely, improvements and
efficiencies can be made to the code segment above.)
http://php.net/manual/en/function.explode.php