递归查找具有特定扩展名的图像

Geo*_*rge 6 php recursion image

我目前正在尝试制作一个脚本,在目录和子目录中找到带有*.jpg/*.png扩展名的图像.

如果找到某些带有这些扩展名的图片,则将其保存到包含路径,名称,大小,高度和宽度的数组中.

到目前为止,我有这段代码,它将找到所有文件,但我不知道如何只获取jpg/png图像.

class ImageCheck {

public static function getDirectory( $path = '.', $level = 0 ){ 

    $ignore = array( 'cgi-bin', '.', '..' ); 
    // Directories to ignore when listing output.

    $dh = @opendir( $path ); 
    // Open the directory to the handle $dh 

    while( false !== ( $file = readdir( $dh ) ) ){ 
    // Loop through the directory 

        if( !in_array( $file, $ignore ) ){ 
        // Check that this file is not to be ignored 

            $spaces = str_repeat( ' ', ( $level * 4 ) ); 
            // Just to add spacing to the list, to better 
            // show the directory tree. 

            if( is_dir( "$path/$file" ) ){ 
            // Its a directory, so we need to keep reading down... 

                echo "<strong>$spaces $file</strong><br />"; 
                ImageCheck::getDirectory( "$path/$file", ($level+1) ); 
                // Re-call this same function but on a new directory. 
                // this is what makes function recursive.  

            } else { 

                echo "$spaces $file<br />"; 
                // Just print out the filename 

            } 

        } 

    } 

    closedir( $dh ); 
    // Close the directory handle 

} 
}
Run Code Online (Sandbox Code Playgroud)

我在我的模板中调用此函数

ImageCheck::getDirectory($dir);
Run Code Online (Sandbox Code Playgroud)

Wob*_*les 12

节省了很多麻烦,只需使用PHP的内置递归搜索和正则表达式:

<?php

$Directory = new RecursiveDirectoryIterator('path/to/project/');
$Iterator = new RecursiveIteratorIterator($Directory);
$Regex = new RegexIterator($Iterator, '/^.+(.jpe?g|.png)$/i', RecursiveRegexIterator::GET_MATCH);

?>
Run Code Online (Sandbox Code Playgroud)

如果您不熟悉使用对象,以下是如何迭代响应:

<?php
foreach($Regex as $name => $Regex){
    echo "$name\n";
}
?>
Run Code Online (Sandbox Code Playgroud)

  • 我可能会将正则表达式调整为''/^.+ \(.jpe?g | .png)$/i'`,但使用SPL时+1 (4认同)