note 47169 deleted from function.explode by bjori
| From: | bjori@php.net | Date: | Mon, 25 Sep 2006 08:12:11 +0000 |
| Subject: | note 47169 deleted from function.explode by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-117601@lists.php.net to get a copy of this message | ||
Note Submitter: ely at DONTSENDGARBGABE dot nauta dot com dot mx
----
I've found very useful the csv_explode function posted by ng4rrjanbiah at rediffmail dot com.
THANKS!
But, [ there is always a but d:o) ], it comes very handy to be able to skip the string delimiter
with a backslash ("\"). Specially if you are using addslashes and stripslashes to create
the CSV line.
Here's my two cents:
<?php
// Explode CSV string
function csv_explode($str, $delim = ',', $qual = "\"")
{
$skipchars = array( $qual, "\\" );
$len = strlen($str);
$inside = false;
$word = '';
for ($i = 0; $i < $len; ++$i) {
if ($str[$i]==$delim && !$inside) {
$out[] = $word;
$word = '';
} else if ($inside && in_array($str[$i], $skipchars) && ($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,"b",c,"this \"should\" work","and
""also"" this"';
echo "test: <pre>".print_r( csv_explode($csv_str), true )."</pre>";
?>
The result would be;
test:
Array
(
[0] => a
[1] => b
[2] => c
[3] => this "should" work
[4] => and "also" this
)