Version: 1.0

Type: Function

Category: Databases

License: GNU General Public License

Description: If you want to get the different arguments out of a comma seperated value line then this snippet is your right choice. it understands quoted arguments and escaped quotes.



<?
function parseCSVline($line) {
	unset($arr);
	
	$quote= ""; $quoteflag= 0; $backslash= 0; $itemindex= 0; unset($item);
	for ($i= 0; $i < strlen($line); $i++) {
		$c= $line{$i};
		
		if ($c == "\\") {
			$backslash= 1-$backslash;
			if ($backslash == 0) $item.= $c;
		}
		else {
			if ($c == "\"" or $c == "'") {
				if($backslash == 0) {
					if ($item == "" and $quoteflag == 0) {
						$quote= $c; $quoteflag= 1;
						
					}
					else {
						if ($c == $quote) {
							if ($quoteflag == 0) {
								print_r($arr);
								return "parse error at position ".$i.": quote not expected\n"; 
							}
							
							$quoteflag= 0;
						}			
						else $item.= $c;
					}
				}		
				else $item.= $c;
				$backslash= 0;
			}
			else {
				if ($c == ",") {
					if ($backslash == 0) {	
						if ($quoteflag == 1) {							
							$item.= $c;
						} 
						else {
							$arr[]= $item;
							unset($item); 
						}
					}
					else $item.= $c;
					
					$backslash= 0;
				} 
				else {
					$item.= $c; // sommige backslash-dingen moeten gebackslasht blijven, bv. \t misschien, maar goed, andere keer
					$backslash= 0;
				}
			}
		}	
		
		
		
		$itemindex++;
	}

	if ($quoteflag == 1) return "parse error at position ".$i.": quote expected\n"; 
	if ($backslash == 1) return "parse error at position ".$i.": backslash expected\n"; 

	$arr[]= $item;	

	return $arr;
}
?>