代码改变世界

PHP glob() 函数用法

2013-06-24 17:11  youxin  阅读(922)  评论(0编辑  收藏  举报

glob() 函数返回匹配指定模式的文件名或目录。

该函数返回一个包含有匹配文件 / 目录的数组。如果出错返回 false。

语法

array glob ( string $pattern [, int $flags = 0 ] )

<?php
print_r(glob("*.txt"));
?>
Array
(
[0] => target.txt
[1] => source.txt
[2] => test.txt
[3] => test2.txt
)
You can fetch multiple file types like this:
// 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 
) 
*/  

Note that the files can actually be returned with a path, depending on your query:

$files = glob('../images/a*.jpg');  
  
print_r($files);  
/* output looks like: 
Array 
( 
    [0] => ../images/apple.jpg 
    [1] => ../images/art.jpg 
) 
*/  

If you want to get the full path to each file, you can just call the realpath() function on the returned values:

$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 
) 
*/  

http://php.net/manual/en/function.glob.php