finding common prefix of array of strings
Posted
by bumperbox
on Stack Overflow
See other posts from Stack Overflow
or by bumperbox
Published on 2009-08-26T17:04:04Z
Indexed on
2010/05/30
2:22 UTC
Read the original article
Hit count: 238
I have an array like this
$sports = array(
'Softball - Counties',
'Softball - Eastern',
'Softball - North Harbour',
'Softball - South',
'Softball - Western'
);
and i would like to find the longest common part of the string so in this instance, it would be 'Softball - ';
I am thinking that I would follow the this process
$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
Questions
is there a built in function or much simpler way of doing this ?
for my 5 line array that is probably fine, but if i were to do several thousand line arrays, there would be a lot of overhead, so i would have to be move calculated with my starting values of $i, eg $i = halfway of string, if it fails, then $i/2 until it works, then increment $i by 1 until we succeed. so that we are doing the least number of comparisons to get a result
If there a formula/algorithm out already out there for this kind of problem ?
thanks
alex
© Stack Overflow or respective owner