查找字符串数组的公共前缀
我有一个这样的数组:
$sports = array(
'Softball - Counties',
'Softball - Eastern',
'Softball - North Harbour',
'Softball - South',
'Softball - Western'
);
我想找到字符串的最长公共前缀。在这种情况下,它将是'Softball - '
我想我会遵循这个过程
$i = 1;
// loop to the length of the first string
while ($i < strlen($sports[0]) {
// grab the left most part up to i in length
$match = substr($sports[0], 0, $i);
// loop through all the values in array, and compare if they match
foreach ($sports as $sport) {
if ($match != substr($sport, 0, $i) {
// didn't match, return the part that did match
return substr($sport, 0, $i-1);
}
} // foreach
// increase string length
$i++;
} // while
// if you got to here, then all of them must be identical
问题
是否有内置函数或更简单的方法来执行此操作?
对于我的5行数组来说,这可能很好,但是如果我要做几千个行数组,会有很多开销,所以我必须用我的起始值移动,例如=字符串的一半,如果它失败了,那么直到它工作,然后递增1直到我们成功。因此,我们正在进行最少数量的比较以获得结果。
$i
$i
$i/2
$i
对于这类问题,有没有一个公式/算法已经存在?