Using PHP to Find Files with Name Containing a Wildcard
When there’s a need to find files within a directory that contain a specific string or extension we can use the PHP function glob(). This can be particularly useful if, for example, we only want image files that end in ‘_thumb’ or when we want to get a list of all the .txt files in a directory.
An example of the above mentioned examples have been demonstrated below:
- // get images containing the string '_thumb'
- foreach (glob("*_thumb.*") as $filename) {
- echo $filename."<br />";
- }
- // get all text files with the extension .txt
- foreach (glob("*.txt") as $filename) {
- echo $filename."<br />";
- }
The glob() function will return an array of filenames that match the pattern provided allowing you to loop through them and do as you wish.
0 comments:
Post a Comment