使用glob()查找文件(转)

时间:2022-12-05 22:59:56
大部分PHP函数的函数名从字面上都可以理解其用途,但是当你看到 glob() 的时候,你也许并不知道这是用来做什么的,其实glob()和scandir() 一样,可以用来查找文件,请看下面的用法: 
  1. // 取得所有的后缀为PHP的文件
  2. $files = glob(‘*.php’);
  3. print_r($files);
  4. /* 输出:
  5. Array
  6. (
  7. [0] => phptest.php
  8. [1] => pi.php
  9. [2] => post_output.php
  10. [3] => test.php
  11. )
  12. */
你还可以查找多种后缀名: 
  1. // 取PHP文件和TXT文件
  2. $files = glob(‘*.{php,txt}’, GLOB_BRACE);
  3. print_r($files);
  4. /* 输出:
  5. Array
  6. (
  7. [0] => phptest.php
  8. [1] => pi.php
  9. [2] => post_output.php
  10. [3] => test.php
  11. [4] => log.txt
  12. [5] => test.txt
  13. )
  14. */
你还可以加上路径: 
  1. $files = glob(‘../images/a*.jpg’);
  2. print_r($files);
  3. /* 输出:
  4. Array
  5. (
  6. [0] => ../images/apple.jpg
  7. [1] => ../images/art.jpg
  8. )
  9. */
如果你想得到绝对路径,你可以调用 realpath() 函数: 
  1. $files = glob(‘../images/a*.jpg’);
  2. // applies the function to each array element
  3. $files = array_map(‘realpath’,$files);
  4. print_r($files);
  5. /* output looks like:
  6. Array
  7. (
  8. [0] => C:\wamp\www\images\apple.jpg
  9. [1] => C:\wamp\www\images\art.jpg
  10. )
  11. */