PHP使用 Glob() 函数查找文件
PHP 中的 glob() 函数比 scandir() 函数功能更为强大,可以按照某种模式搜索文件。- // get all php files
- $files = glob('*.php');
- print_r($files);
- /* output looks like:
- Array
- (
- [0] => phptest.php
- [1] => pi.php
- [2] => post_output.php
- [3] => test.php
- )
- */
复制代码 你可以像这样获得多个文件:- // get all php files AND txt files
- $files = glob('*.{php,txt}', GLOB_BRACE);
- print_r($files);
- /* output looks like:
- Array
- (
- [0] => phptest.php
- [1] => pi.php
- [2] => post_output.php
- [3] => test.php
- [4] => log.txt
- [5] => test.txt
- )
- */
复制代码 请注意,这些文件其实是可以返回一个路径,这取决于查询条件:- $files = glob('../images/a*.jpg');
- print_r($files);
- /* output looks like:
- Array
- (
- [0] => ../images/apple.jpg
- [1] => ../images/art.jpg
- )
- */
复制代码 如果你想获得每个文件的完整路径,你可以调用 realpath() 函数:- $files = glob('../images/a*.jpg');
- // applies the function to each array element
- $files = array_map('realpath',$files);
- print_r($files);
- /* output looks like:
- Array
- (
- [0] => C:\wamp\www\images\apple.jpg
- [1] => C:\wamp\www\images\art.jpg
- )
- */
复制代码 |