Is there a way to glob() only files?

元气小坏坏 提交于 2019-11-30 07:53:43
Alain Tiemblo

I finally found a solution :

echo "Only files\n";
$files = array_filter(glob("/*"), 'is_file');
var_dump($files);

But take care, array_filter will preserve numeric keys : use array_values if you need to reindex the array.

You can use GLOB_BRACE to match documents against a list of known file extensions:

$files = glob("/path/to/directory/*.{jpg,gif,png,html,htm,php,ini}", GLOB_BRACE);

see: http://www.electrictoolbox.com/php-glob-find-files/

There is an easier way, just one line:

$files = glob("/path/to/directory/*.{*}", GLOB_BRACE);

the {*} means all file endings, so every file, but no folder!

10% faster compared to the solution of @AlainTiemblo :

$files = array_filter(glob("/*", GLOB_MARK), function($path){ return $path[ strlen($path) - 1 ] != '/'; });

It uses GLOB_MARK to add a slash to each directory and by that we are able to remove those entries through array_filter() and an anonymous function.

Since PHP 7.1.0 supports Negative numeric indices you can use this instead, too:

$files = array_filter(glob("/*", GLOB_MARK), function($path){return $path[-1] != '/';});

No relevant speed gain, but it helps avoiding the stackoverflow scrollbar ^^

As array_filter() preserve the keys you should consider re-indexing the array with array_values() afterwards:

$files = array_values($files);
$all = glob("/*.*");

this will list everything with a "." after the file name. so basically, all files.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!