note 37004 modified in function.explode by aidan
| From: | aidan@php.net | Date: | Sun, 27 Jun 2004 14:12:48 +0000 |
| Subject: | note 37004 modified in function.explode by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-71911@lists.php.net to get a copy of this message | ||
The improved CSV Explode function of "hhromic at udec dot cl" again has one limitation
with MS Excel.
His version returns "" for """". But the expected result is " for
""""
And so, I have modified his code with additional inside check.
<?php
// Explode CSV (MS Excel) string
function csv_explode($str, $delim = ',', $qual = "\"")
{
$len = strlen($str);
$inside = false;
$word = '';
for ($i = 0; $i < $len; ++$i) {
if ($str[$i]==$delim && !$inside) {
$out[] = $word;
$word = '';
} else if ($inside && $str[$i]==$qual && ($i<$len &&
$str[$i+1]==$qual)) {
$word .= $qual;
++$i;
} else if ($str[$i] == $qual) {
$inside = !$inside;
} else {
$word .= $str[$i];
}
}
$out[] = $word;
return $out;
}
// Test...
$csv_str = 'a,"""","""",d,e,f';
print_r( csv_explode($csv_str) );
?>
HTH,
R. Rajesh Jeba Anbiah
--was--
The improved CSV Explode function of "hhromic at udec dot cl" again has one limitation
with MS Excel.
His version returns "" for """". But the expected result is "
for """"
And so, I have modified his code with additional inside check.
<?php
//Explode CSV (MS Excel) string
function csv_explode($str, $delim = ',', $qual = "\"")
{
$len = strlen($str);
$inside = false;
$word = '';
for ($i = 0; $i < $len; ++$i) {
if ($str[$i]==$delim && !$inside) {
$out[] = $word;
$word = '';
} else if ($inside && $str[$i]==$qual && ($i<$len &&
$str[$i+1]==$qual)) {
$word .= $qual;
++$i;
} else if ($str[$i] == $qual) {
$inside = !$inside;
} else {
$word .= $str[$i];
}
}
$out[] = $word;
return $out;
} /*-------csv_explode()------------*/
//Test...
$csv_str = 'a,"""","""",d,e,f';
print_r( csv_explode($csv_str) );
?>
HTH,
R. Rajesh Jeba Anbiah
http://php.net/manual/en/function.explode.php