Search code examples
phplistdirectoryclosest

Get the closest directory from a list


I have a dinamic array of directories like this:

array(4) {
  [0]=>
  string(34) "C:\www\www\mb\core"
  [1]=>
  string(59) "C:\www\www\mb\core\plugins\enabled\response"
  [2]=>
  string(56) "C:\www\www\mb\core\plugins\enabled\tests"
  [3]=>
  string(52) "C:\www\www\mb\core\templates\default"
}

And I have another directory to test: C:\www\www\mb\core\plugins\enabled\includes

I need to know what directory is the closest one to this one, by a function. Everything here is unknown and dynamic. I've tried with foreach+strpos+string size but it was becoming so ugly that I stopped and came here for help, and it didn't work too. :-P

Thanks in advance and sorry for my bad English,

Vinicius


Solution

  • Well, I would do exactly what you described…

    function closest_path($path, $paths) {
        $maxMatch = null;
        $maxMatchLength = 0;
    
        foreach($paths as $item) {
            if(strlen($item) > $maxMatchLength && strpos($path, $item) === 0) {
                $maxMatch = $item;
                $maxMatchLength = strlen($item);
            }
        }
    
        return $maxMatch;
    }