finding common prefix of array of strings

后端 未结 17 1662
一向
一向 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:48

    This is an addition to the @Gumbo answer. If you want to ensure that the chosen, common prefix does not break words, use this. I am just having it look for a blank space at the end of the chosen string. If that exists we know that there was more to all of the phrases, so we truncate it.

    function product_name_intersection($array){
    
        $pl = 0; // common prefix length
        $n = count($array);
        $l = strlen($array[0]);
        $first = current($array);
    
        while ($pl < $l) {
            $c = $array[0][$pl];
            for ($i=1; $i<$n; $i++) {
                if (!isset($array[$i][$pl]) || $array[$i][$pl] !== $c) break 2;
            }
            $pl++;
        }
        $prefix = substr($array[0], 0, $pl);
    
        if ($pl < strlen($first) && substr($prefix, -1, 1) != ' ') {
    
            $prefix = preg_replace('/\W\w+\s*(\W*)$/', '$1', $prefix);
        }
    
        $prefix =  preg_replace('/^\W*(.+?)\W*$/', '$1', $prefix);
    
        return $prefix;
    }
    

提交回复
热议问题