How to find the longest common prefix of all the words in a string with PHP

1 Answer

0 votes
function longestCommonPrefix(string $input): string 
{
    if (trim($input) === '') {
        return '';
    }

    // Split by non‑word characters (same as Java's split("\\W+"))
    $words = preg_split('/\W+/', strtolower($input), -1, PREG_SPLIT_NO_EMPTY);

    if (empty($words)) {
        return '';
    }

    $prefix = $words[0];

    foreach ($words as $word) {
        while (strpos($word, $prefix) !== 0) {
            $prefix = substr($prefix, 0, -1);
            if ($prefix === '') {
                return '';
            }
        }
    }

    return $prefix;
}

$s1 = "The lowly inhabitants of the lowland were surprised to see the lower branches.";
echo "LCP: '" . longestCommonPrefix($s1) . "'\n";

$s2 = "unclear, uncertain, unexpected";
echo "LCP: '" . longestCommonPrefix($s2) . "'\n";




/*
run:

LCP: ''
LCP: 'un'

*/

 



answered Mar 11 by avibootz

Related questions

...