How to group words in a string by the first N letters in PHP

2 Answers

0 votes
function groupByFirstNLetters(string $s, int $n = 3): array {
    preg_match_all('/[A-Za-z]+/', strtolower($s), $matches);
    $words = $matches[0];

    $groups = [];

    foreach ($words as $w) {
        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

*/

 



answered Mar 13 by avibootz
0 votes
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

*/

 



answered Mar 13 by avibootz
...