Recursive File Search (PHP)

前端 未结 8 920
逝去的感伤
逝去的感伤 2020-11-29 07:57

I\'m trying to return the files in a specified directory using a recursive search. I successfully achieved this, however I want to add a few lines of code that will allow me

相关标签:
8条回答
  • 2020-11-29 09:01

    Try this, it uses an array of allowed file types and only echos out the file if the file extension exists within the array.

    <?php
    $it = new RecursiveDirectoryIterator("L:\folder\folder\folder");
    $allowed=array("pdf","txt");
    foreach(new RecursiveIteratorIterator($it) as $file) {
        if(in_array(substr($file, strrpos($file, '.') + 1),$allowed)) {
            echo $file . "<br/> \n";
        }
    }
    ?>
    

    You may also find that you could pass an array of allowed file types to your RecursiveDirectoryIterator class and only return files that match.

    0 讨论(0)
  • 2020-11-29 09:02

    None of these worked for my case. So i wrote this function, not sure about efficiency, I just wanted to remove some duplicate photos quickly. Hope it helps someone else.

    function rglob($dir, $pattern, $matches=array())
    {
        $dir_list = glob($dir . '*/');
        $pattern_match = glob($dir . $pattern);
    
        $matches = array_merge($matches, $pattern_match);
    
        foreach($dir_list as $directory)
        {
            $matches = rglob($directory, $pattern, $matches);
        }
    
        return $matches;
    }
    
    $matches = rglob("C:/Bridge/", '*(2).ARW');
    

    Only slight improvement that could be made is that currently for it to work you have to have a trailing forward slash on the start directory.

    0 讨论(0)
提交回复
热议问题