note 81490 added to function.split
| From: | DaveWalter at osu1 dot php dot net | Date: | Fri, 29 Feb 2008 23:39:15 +0000 |
| Subject: | note 81490 added to function.split | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-136623@lists.php.net to get a copy of this message | ||
In response to the getCSVValues() function posted by justin at cam dot org, my testing indicates
that it has a problem with a CSV string like this:
1,2,"3,""4,5"",6",7
This parses as:
array(6) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(4) "3,"4"
[3]=>
string(1) "5"
[4]=>
string(0) ""
[5]=>
string(1) "7"
}
instead of:
array(4) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(9) "3,"4,5",6"
[3]=>
string(1) "7"
}
To fix this, I changed the second substr_count to look for an odd number of quotes, as opposed to
any quotes at all:
<?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], '"') %2 == 1) { // Look for an
odd-number of quotes
// 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: 75.49.241.185
----
Manual Page -- http://www.php.net/manual/en/function.split.php
Edit -- https://master.php.net/note/edit/81490
Del: integrated -- https://master.php.net/note/delete/81490/integrated
Del: useless -- https://master.php.net/note/delete/81490/useless
Del: bad code -- https://master.php.net/note/delete/81490/bad+code
Del: spam -- https://master.php.net/note/delete/81490/spam
Del: non-english -- https://master.php.net/note/delete/81490/non-english
Del: in docs -- https://master.php.net/note/delete/81490/in+docs
Del: other reasons-- https://master.php.net/note/delete/81490
Reject -- https://master.php.net/note/reject/81490
Search -- https://master.php.net/manage/user-notes.php