Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Last active April 29, 2019 09:24
Show Gist options
  • Save kobus1998/37fb9b8d69a90e03ef5eba40d55f2df9 to your computer and use it in GitHub Desktop.
Save kobus1998/37fb9b8d69a90e03ef5eba40d55f2df9 to your computer and use it in GitHub Desktop.
Detect csv delimiter
<?php
class UnsupportedDelimiter extends \Exception
{
}
class Csv
{
public function __construct(string $csv)
{
$this->raw = $csv;
}
public function getDelimiter()
{
if (preg_match("/^\w*,/", $this->raw)) {
return ',';
} elseif (preg_match("/^\w*;/", $this->raw)) {
return ';';
}
throw new UnsupportedDelimiter("Could not detect valid delimiter");
}
}
$csvFile ="name;email;xxx
aaaa;[email protected];kjns
";
$csv = new Csv($csvFile);
echo $csv->getDelimiter(); // ;
$csvFile2 ="name,email,xxx
aaaa,[email protected],kjns
";
$csv2 = new Csv($csvFile2);
echo $csv2->getDelimiter(); // ,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment