how to find out if csv file fields are tab delimited or comma delimited

后端 未结 15 997
[愿得一人]
[愿得一人] 2020-12-01 09:46

how to find out if csv file fields are tab delimited or comma delimited. I need php validation for this. Can anyone plz help. Thanks in advance.

15条回答
  •  攒了一身酷
    2020-12-01 10:32

    I'm just counting the occurrences of the different delimiters in the CSV file, the one with the most should probably be the correct delimiter:

    //The delimiters array to look through
    $delimiters = array(
        'semicolon' => ";",
        'tab'       => "\t",
        'comma'     => ",",
    );
    
    //Load the csv file into a string
    $csv = file_get_contents($file);
    foreach ($delimiters as $key => $delim) {
        $res[$key] = substr_count($csv, $delim);
    }
    
    //reverse sort the values, so the [0] element has the most occured delimiter
    arsort($res);
    
    reset($res);
    $first_key = key($res);
    
    return $delimiters[$first_key]; 
    

提交回复
热议问题