finding common prefix of array of strings

后端 未结 17 1699
一向
一向 2020-11-29 06:15

I have an array like this:

$sports = array(
\'Softball - Counties\',
\'Softball - Eastern\',
\'Softball - North Harbour\',
\'Softball - South\',
\'Softball -         


        
17条回答
  •  盖世英雄少女心
    2020-11-29 06:43

    If you can sort your array, then there is a simple and very fast solution.

    Simply compare the first item to the last one.

    If the strings are sorted, any prefix common to all strings will be common to the sorted first and last strings.

    sort($sport);
    
    $s1 = $sport[0];               // First string
    $s2 = $sport[count($sport)-1]; // Last string
    $len = min(strlen($s1), strlen($s2));
    
    // While we still have string to compare,
    // if the indexed character is the same in both strings,
    // increment the index. 
    for ($i=0; $i<$len && $s1[$i]==$s2[$i]; $i++); 
    
    $prefix = substr($s1, 0, $i);
    

提交回复
热议问题