Last active
April 29, 2019 09:24
-
-
Save kobus1998/37fb9b8d69a90e03ef5eba40d55f2df9 to your computer and use it in GitHub Desktop.
Detect csv delimiter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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