public static function parseString($string, $separator = ',') { $values = array(); $string = str_replace("\r\n", '', $string); // eat the traling new line, if any if ($string == '') { return $values; } $tokens = explode($separator, $string); $count = count($tokens); for ($i = 0; $i < $count; $i++) { $token = $tokens[$i]; $len = strlen($token); $newValue = ''; if ($len > 0 and $token[0] == '"') { // if quoted $token = substr($token, 1); // remove leading quote do { // concatenate with next token while incomplete $complete = Csv::_hasEndQuote($token); $token = str_replace('""', '"', $token); // unescape escaped quotes $len = strlen($token); if ($complete) { // if complete $newValue .= substr($token, 0, -1); // remove trailing quote } else { // incomplete, get one more token $newValue .= $token; $newValue .= $separator; if ($i == $count - 1) { throw new Exception('Illegal unescaped quote.'); } $token = $tokens[++$i]; } } while (!$complete); } else { // unescaped, use token as is $newValue .= $token; } $values[] = $newValue; } return $values; }
function testHasEndQuote_EndWithOneEscapedQuoteWithQuotesInside() { $result = Csv::_hasEndQuote('a strin"g""'); $this->assertFalse($result); }