function groupByFirstNLetters(string $s, int $n = 3): array {
preg_match_all('/[A-Za-z]+/', strtolower($s), $matches);
return array_reduce($matches[0], function ($groups, $w) use ($n) {
if (strlen($w) >= $n) {
$prefix = substr($w, 0, $n);
$groups[$prefix][] = $w;
}
return $groups;
}, []);
}
$s = "The lowly inhabitants of the lowland were surprised to see the lower branches of the trees.";
$groups = groupByFirstNLetters($s, 3);
foreach ($groups as $prefix => $words) {
echo "$prefix: " . implode(", ", $words) . "\n";
}
/*
run:
the: the, the, the, the
low: lowly, lowland, lower
inh: inhabitants
wer: were
sur: surprised
see: see
bra: branches
tre: trees
*/