Home > Article > Backend Development > How to use the glob function in PHP to get a list of files matching a specified pattern
In PHP, if you want to get a list of files matching a specified pattern, you can use the glob function. The glob function can return a list of file names or paths for all files matching a specified pattern.
The syntax of the glob function is as follows:
array glob ( string $pattern [, int $flags = 0 ] )
Among them, the $pattern parameter specifies the file pattern to be matched, which can include wildcards (*, ?, etc.). The $flags parameter is optional and can be used to instruct the glob function to consider file types and other options when retrieving the directory.
The following is a simple example that demonstrates how to use the glob function to get the file name list of all txt files:
$files = glob("*.txt"); foreach ($files as $file) { echo $file . "<br>"; }
In this example, we set the matching pattern to "*.txt ”, which means we want to get all files with the extension “txt”. The glob function will return a list of file names for all files matching the pattern. We can then use a foreach loop to iterate through this list and output the filename of each file one by one.
In addition to basic wildcards, we can also include directory paths in patterns. For example, if we want to get all files named "*.txt" and these files are located in the "/home/user/files/" directory, we can use the following code:
$files = glob("/home/user/files/*.txt"); foreach ($files as $file) { echo $file . "<br>"; }
In this example , we specified the directory path "/home/user/files/" and then appended a wildcard and file extension. The glob function will return a list of file names for all files matching the pattern.
If we want to get all image files with extension "jpg" or "png", we can use the following code:
$files = glob("*.{jpg,png}", GLOB_BRACE); foreach ($files as $file) { echo $file . "<br>"; }
Here, we use curly braces to create an extension A list of names (i.e. "{jpg,png}"). We also pass the GLOB_BRACE flag into the glob function to indicate that it should interpret the curly braces as a list of extensions. In this way, the glob function will return a list of file names for all files with the extension "jpg" or "png".
In addition to the several usages mentioned above, the glob function also supports many other options and functions, such as recursively searching directories, filtering results, etc. See the PHP documentation for more information and examples.
The above is the detailed content of How to use the glob function in PHP to get a list of files matching a specified pattern. For more information, please follow other related articles on the PHP Chinese website!