Tetris-ing an array

后端 未结 16 1545
时光取名叫无心
时光取名叫无心 2021-01-30 15:38

Consider the following array:

/www/htdocs/1/sites/lib/abcdedd
/www/htdocs/1/sites/conf/xyz
/www/htdocs/1/sites/conf/abc/         


        
16条回答
  •  独厮守ぢ
    2021-01-30 16:21

    I'll throw my hat in the ring …

    function longestCommonPrefix($a, $b) {
        $i = 0;
        $end = min(strlen($a), strlen($b));
        while ($i < $end && $a[$i] == $b[$i]) $i++;
        return substr($a, 0, $i);
    }
    
    function longestCommonPrefixFromArray(array $strings) {
        $count = count($strings);
        if (!$count) return '';
        $prefix = reset($strings);
        for ($i = 1; $i < $count; $i++)
            $prefix = longestCommonPrefix($prefix, $strings[$i]);
        return $prefix;
    }
    
    function stripPrefix(&$string, $foo, $length) {
        $string = substr($string, $length);
    }
    

    Usage:

    $paths = array(
        '/www/htdocs/1/sites/lib/abcdedd',
        '/www/htdocs/1/sites/conf/xyz',
        '/www/htdocs/1/sites/conf/abc/def',
        '/www/htdocs/1/sites/htdocs/xyz',
        '/www/htdocs/1/sites/lib2/abcdedd',
    );
    
    $longComPref = longestCommonPrefixFromArray($paths);
    array_walk($paths, 'stripPrefix', strlen($longComPref));
    print_r($paths);
    

提交回复
热议问题