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'
*/