Home > php教程 > PHP视频 > Detailed explanation of how PHP uses the glob function to traverse files and directories

Detailed explanation of how PHP uses the glob function to traverse files and directories

高洛峰
Release: 2016-12-21 16:17:45
Original
1622 people have browsed it

php glob() function returns the file name or directory matching the specified pattern. Therefore, we can use the glob function to find files and traverse directories.

Function description: array glob (string $pattern [, int $flags])

Function: Find the file path that matches the pattern and return an array containing the matching files (directories) (Note: The file being checked must be a server system (cannot be used for remote files)

Parameter description: first parameter: matching pattern; second optional parameter:

GLOB_MARK - add a slash to each returned item

GLOB_NOSORT - follow the file in Original order of occurrences in directory returned (not sorted)

GLOB_NOCHECK - Returns pattern used for search if no files match

GLOB_NOESCAPE - Backslash unescaped metacharacters

GLOB_BRACE - Extended {a,b,c} to match 'a', 'b' or 'c'

GLOB_ONLYDIR - Return only directory entries matching the pattern

Example 1: Get all files and subdirectories under the specified directory

<?php
   $directories = glob("/tmp/*", GLOB_ONLYDIR);//获取/tmp/目录下的所有目录
   $complete = glob("/tmp/*");//获取/tmp/目录下的所有目录和文件
   $files = array_diff($directories, $complete);//获取/tmp/目录下的所有文件
 
   echo "Directories in /tmp/<BR>";
   foreach($directories as $val) {
     echo "$val<BR>\n";
   }
   echo "<BR>Files in /tmp/<BR>";
   foreach($files as $val) {
     echo "$val<BR>\n";
   }
?>
Copy after login

Example 2: You Are you still using opendir readdir to traverse files? You are really out!

<?php
$files = glob("dir/*.jpg");
foreach($files as $jpg){
  echo $jpg, "\n";
}
?>
Copy after login

The above is a compilation of information on how to use the glob function in PHP to traverse files and directories. We will continue to add relevant information in the future. Thank you for your support of this site!

For more detailed explanations of how PHP uses the glob function to traverse files and directories, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template