简体   繁体   English

php - 用于搜索目录和仅限.jpg的glob

[英]php--glob for searching directories and .jpg only

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. 我有一个名为“stuff”的文件夹,其中上传了随机内容。 And say I want to search for just subfolders AND .jpg files within “stuff” and nothing more. 并说我想在“东西”中搜索子文件夹和.jpg文件,仅此而已。 I know to search for only .jpg is… 我知道只搜索.jpg是...

$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? 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
    }
}

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

If you want it to do other things to the individual file, just replace the print "$file\\n" part. 如果您希望它对单个文件执行其他操作,只需替换print "$file\\n"部分。

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. 该函数可以在其glob搜索中更具体,只匹配目录以及具有指定文件扩展名的文件,但我这样做是为了简化和透明。

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文件数组stuff/中也子目录stuff/将更进一步把你的代码:

$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>");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM