<?php
$input = 'имя1;им,я2;имя3
имя4;имя5;имя6
,имя7;имя,8;имя,9';
function detectSeparator(string $str): string|false
{
$rows = explode("\n", $str);
$rowCounts = [
'tab' => [
'symbol' => "\t",
'occurs' => [],
'maxOccurs' => 0,
'maxOccursInRow' => 0,
],
'comma' => [
'symbol' => ',',
'occurs' => [],
'maxOccurs' => 0,
'maxOccursInRow' => 0,
],
'semicolon' => [
'symbol' => ';',
'occurs' => [],
'maxOccurs' => 0,
'maxOccursInRow' => 0,
],
];
foreach ($rows as $row) {
$tabsCount = substr_count($row, "\t");
$rowCounts['tab']['occurs'][$tabsCount]++;
$commasCount = substr_count($row, ',');
$rowCounts['comma']['occurs'][$commasCount]++;
$semicolonsCount = substr_count($row, ';');
$rowCounts['semicolon']['occurs'][$semicolonsCount]++;
}
foreach ($rowCounts as &$symbol) {
if (empty($symbol['occurs'])) continue;
krsort($symbol['occurs']);
$maxOccurs = array_key_first($symbol['occurs']);
$maxOccursByRow = $symbol['occurs'][$maxOccurs];
$symbol['maxOccurs'] = $maxOccurs;
$symbol['maxOccursInRow'] = $maxOccursByRow;
}
unset($symbol); // prevent possible side-effects
usort($rowCounts, function ($first, $second) {
return $first['maxOccurs'] !== $second['maxOccurs'];
});
usort($rowCounts, function ($first, $second) {
return $first['maxOccursInRow'] !== $second['maxOccursInRow'];
});
$topSymbol = $rowCounts[0];
if ($topSymbol['maxOccurs'] === 0) {
return false;
}
return $topSymbol['symbol'];
}
var_dump(detectSeparator($input)); // ; должно вернуть