note 73286 added to function.split
| From: | justin at cam dot org | Date: | Fri, 16 Feb 2007 06:21:48 +0000 |
| Subject: | note 73286 added to function.split | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-123474@lists.php.net to get a copy of this message | ||
The previous solution assumes that a quoted string always starts a new element (true in real CSV
files, but not in my application). The following routine does not make any such assumptions. It also
deals with pairs of quotes and does not use any regular expressions.
<?php
function getCSVValues($string, $separator=",")
{
$elements = explode($separator, $string);
for ($i = 0; $i < count($elements); $i++) {
$nquotes = substr_count($elements[$i], '"');
if ($nquotes %2 == 1) {
for ($j = $i+1; $j < count($elements); $j++) {
if (substr_count($elements[$j], '"') > 0) {
// Put the quoted string's pieces back together again
array_splice($elements, $i, $j-$i+1,
implode($separator, array_slice($elements, $i, $j-$i+1)));
break;
}
}
}
if ($nquotes > 0) {
// Remove first and last quotes, then merge pairs of quotes
$qstr =& $elements[$i];
$qstr = substr_replace($qstr, '', strpos($qstr, '"'), 1);
$qstr = substr_replace($qstr, '', strrpos($qstr, '"'), 1);
$qstr = str_replace('""', '"', $qstr);
}
}
return $elements;
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 74.13.164.105
----
Manual Page -- http://www.php.net/manual/en/function.split.php
Edit -- https://master.php.net/note/edit/73286
Del: integrated -- https://master.php.net/note/delete/73286/integrated
Del: useless -- https://master.php.net/note/delete/73286/useless
Del: bad code -- https://master.php.net/note/delete/73286/bad+code
Del: spam -- https://master.php.net/note/delete/73286/spam
Del: non-english -- https://master.php.net/note/delete/73286/non-english
Del: in docs -- https://master.php.net/note/delete/73286/in+docs
Del: other reasons-- https://master.php.net/note/delete/73286
Reject -- https://master.php.net/note/reject/73286
Search -- https://master.php.net/manage/user-notes.php