finding common prefix of array of strings

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

I have an array like this:

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


        
17条回答
  •  旧时难觅i
    2020-11-29 06:41

    For what it's worth, here's another alternative I came up with.

    I used this for finding the common prefix for a list of products codes (ie. where there are multiple product SKUs that have a common series of characters at the start):

    /**
     * Try to find a common prefix for a list of strings
     * 
     * @param array $strings
     * @return string
     */
    function findCommonPrefix(array $strings)
    {
        $prefix = '';
        $chars = array_map("str_split", $strings);
        $matches = call_user_func_array("array_intersect_assoc", $chars);
        if ($matches) {
            $i = 0;
            foreach ($matches as $key => $value) {
                if ($key != $i) {
                    unset($matches[$key]);
                }
                $i++;
            }
            $prefix = join('', $matches);
        }
    
        return $prefix;
    }
    

提交回复
热议问题