php--glob仅用于搜索目录和.jpg [英] php--glob for searching directories and .jpg only

查看:86
本文介绍了php--glob仅用于搜索目录和.jpg的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我只想搜索子目录和某些文件类型,该怎么办. 前任.我有一个名为"stuff"的文件夹,其中上传了随机的东西.并说我只想在东西"中搜索子文件夹和.jpg文件,仅此而已.我知道只搜索.jpg是…

What if I want to search for a only subdirectories AND certain file types. Ex. I have a folder named "stuff" where random stuff is uploaded. And say I want to search for just subfolders AND .jpg files within "stuff" and nothing more. I know to search for only .jpg is…

$array = glob(‘stuff/{*.jpg}’, GLOB_BRACE);

仅搜索子目录是...

and to search for only subdirectories is…

$array = glob(‘stuff/*’, GLOB_ONLYDIR);

...但是如何在不获取其他不需要文件的情况下将两者结合起来? GLOB_BRACE的子行业是否有某种模式?

…but how do I combine the two without getting any other unwanted files? Is there a pattern for subirectories for GLOB_BRACE?

推荐答案

此递归函数应该可以解决问题:

This recursive function should do the trick:

function recursiveGlob($dir, $ext) {
    $globFiles = glob("$dir/*.$ext");
    $globDirs  = glob("$dir/*", GLOB_ONLYDIR);

    foreach ($globDirs as $dir) {
        recursiveGlob($dir, $ext);
    }

    foreach ($globFiles as $file) {
        print "$file\n"; // Replace '\n' with '<br />' if outputting to browser
    }
}

用法:recursiveGlob('C:\Some\Dir', 'jpg');

如果您希望它对单个文件执行其他操作,只需替换print "$file\n"部分.

If you want it to do other things to the individual file, just replace the print "$file\n" part.

该函数可以在其glob搜索中更加具体,并且仅匹配目录以及具有指定文件扩展名的文件,但是我这样做是出于简单和透明的目的.

The function can be more specific in its glob searches and only match directories as well as files with the specified file extension, but I made it this way for simplicity and transparency.

这篇关于php--glob仅用于搜索目录和.jpg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆