Skip to content

Instantly share code, notes, and snippets.

@daithi-coombes
Created March 5, 2014 10:45
Show Gist options
  • Save daithi-coombes/9364996 to your computer and use it in GitHub Desktop.
Save daithi-coombes/9364996 to your computer and use it in GitHub Desktop.
/**
* Detect delimiter.
* @param integer $depth The number of lines from csv file to work with.
* @param array $chars Optional. An array of characters to guess.
* @param array $lines Sample lines from csv file.
* @return string Returns the best guess.
*/
private function detect_delimiter( $depth=20, $chars=null, $lines ){
if( !$chars )
$chars = array(',','|','\t',';','.',':',);
$auto_non_chars = "a-zA-Z0-9\n\r";
$guesses = array();
foreach($lines as $key => $line)
foreach( $chars as $char )
$res[$char][$key] = count( explode($char, $line) );
foreach($res as $char => $r){
$c = array_count_values($r);
//return first delimiter that was found in all rows
if( count($c)===1 )
$guesses[$char] = array_shift($c);
}
asort( $guesses );
end($guesses);
return key( $guesses );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment