Wednesday, April 11, 2018

Using PHP's glob() function to find files in a directory | Filter files in directory | Regex filter files in directory

The examples below look at a directory with the following, the same example directory as used in the read through directory post
To find all the files in the directory /path/to/directory with a .txt file extension, you can do this:
$files = glob("/path/to/directory/*.txt");
Array
(
    [0] => /path/to/directory/bar.txt
    [1] => /path/to/directory/foo.txt
    [2] => /path/to/directory/link2foo.txt
)
There are flags which can be passed as a second optional parameter. One of these is GLOB_BRACE which means that e.g. {jpg,gif,png} will be expanded to match jpg, gif and png which can be useful if you need to look for a particular set of files by their extension, in this example for image files
$files = glob("/path/to/directory/*.{jpg,gif,png}", GLOB_BRACE);
Array
(
    [0] => /path/to/directory/1.jpg
    [1] => /path/to/directory/2.gif
    [2] => /path/to/directory/3.png
)

No comments:

Post a Comment