列出多个文件扩展名的 PHP 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10591530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP file listing multiple file extensions
提问by user1383147
Here is my current code:
这是我当前的代码:
$files = glob("*.jpg");
This works fine. However, I am wanting to list other image types, such as .png, gif etc.
这工作正常。但是,我想列出其他图像类型,例如 .png、gif 等。
Can I please have some help to modify this above code to get it working. I have tried the following with no success:
我可以请一些帮助来修改上面的代码以使其正常工作。我尝试了以下方法但没有成功:
$files = glob("*.jpg","*.png","*.gif");
$files = glob("*.jpg,*.png,*.gif);
And other variations...
和其他变化...
回答by Jeroen
$files = glob("*.{jpg,png,gif}", GLOB_BRACE);
回答by Marco Santana
My two cents:
我的两分钱:
$availableImageFormats = [
"png",
"jpg",
"jpeg",
"gif"];
$searchDir = /*yourDir*/;
$imageExtensions = "{";
foreach ($availableImageFormats as $extension) {
$extensionChars = str_split($extension);
$rgxPartial = null;
foreach ($extensionChars as $char) {
$rgxPartial .= "[".strtoupper($char).strtolower($char)."]";
}
$rgxPartial .= ",";
$imageExtensions .= $rgxPartial;
};
$imageExtensions .= "}";
glob($searchDir."/*.".$imageExtensions, GLOB_BRACE)
With this you can create an array of all the extensions you are looking for without worrying of improper case use. Hope it helps
有了这个,您可以创建您正在寻找的所有扩展的数组,而不必担心不正确的案例使用。希望能帮助到你
回答by Jens T?rnell
I just needed this for my own project. I made a converter from array to string.
我只是在我自己的项目中需要这个。我做了一个从数组到字符串的转换器。
function whitelistToBrace($whitelist) {
$str = "{";
$whitelist = !empty($whitelist) ? $whitelist : ['*'];
foreach($whitelist as $extension) {
$str .= '*.' . strtolower($extension) . ',';
};
$str = substr($str, 0, -1) . '}';
return $str;
}
Usage
用法
$whitelist = [
'png',
'jpg'
];
// glob('my/path/*.{*.png,*.jpg}', GLOB_BRACE);
$glob = glob('my/path/' . whitelistToBrace($whitelist), GLOB_BRACE);
print_r($glob);

