欢迎访问 舍力博客(www.shuyong.net)
在PHP中递归遍历目录并过滤出图片文件,你可以使用scandir()函数配合is_dir()函数来遍历目录和子目录,然后使用pathinfo()函数来检查文件扩展名,从而过滤出图片文件。以下是一个简单的示例,演示如何实现这一功能:
<?php
// 配置部分
$excludeDirs = ['khimg','tuku2025']; // 要排除的目录
$baseDir = '../'; // 基准目录
$directory = new RecursiveDirectoryIterator($baseDir, RecursiveDirectoryIterator::SKIP_DOTS);// 创建递归目录迭代器
// 创建目录过滤器
$filter = new RecursiveCallbackFilterIterator($directory,
function($current) use ($excludeDirs, $baseDir) {
if($current->isDir()) {// 获取相对基准目录的路径
$relativePath = str_replace(realpath($baseDir).DIRECTORY_SEPARATOR,'',$current->getRealPath());
foreach($excludeDirs as $exclude){if(strpos($relativePath, $exclude) === 0){return false;}}}return true;});// 检查是否在排除列表
$iterator = new RecursiveIteratorIterator($filter,RecursiveIteratorIterator::SELF_FIRST);// 创建递归迭代器
$regex = new RegexIterator($iterator,'/^.+\.(jpg|jpeg|png|gif)$/i',RecursiveRegexIterator::GET_MATCH);// 匹配图片文件
// 按目录分类存储
$categorized = [];
foreach ($regex as $match) {
$fullPath = $match[0]; // 完整文件路径
$dir = str_replace('\\', '/', dirname($fullPath));// 获取标准化目录路径(统一使用斜杠)
if(!isset($categorized[$dir])){$categorized[$dir] = [];}// 初始化目录存储空间
//$categorized[$dir][] = basename($fullPath);// 存储文件名(带扩展名)
$categorized[$dir][] = $fullPath; //完整文件名路径
}
?>
调用方法:
<?php
foreach($categorized as $dir => $files) {
$shortDir = str_replace('../', '', $dir);
if(count($files)>1){echo $shortDir;echo count($files);
foreach($files as $file) {echo $file;}
}}
?>
演示地址:http://img.kh.syom.cn/tuku2025/

留言/评论:◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。