问题
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);
…but how do I combine the two without getting any other unwanted files? Is there a pattern for subirectories for GLOB_BRACE?
回答1:
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
}
}
Usage: recursiveGlob('C:\Some\Dir', 'jpg');
If you want it to do other things to the individual file, just replace the print "$file\n"
part.
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.
回答2:
I'm not sure I am following exactly because with one you are looking for a specific file type, and with the other you are looking for subdirectories. Those are completely different patterns!
That being said, a way to have an array containing all *.jpg files in stuff/
and also subdirectories in stuff/
would be to take your code a step further:
$jpg_array = glob('stuff/{*.jpg}', GLOB_BRACE);
$subdir_array = glob('stuff/*', GLOB_ONLYDIR);
// Combine arrays
$items = array_merge($jpg_array,$subdir_array);
// Do something with values
foreach($items as $item)
{
echo($item . "<br>");
}
来源:https://stackoverflow.com/questions/9755458/php-glob-for-searching-directories-and-jpg-only