Tuesday 17 July 2018

Using PHP to Find Files with Name Containing a Wildcard

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:

  1. // get images containing the string '_thumb'  
  2. foreach (glob("*_thumb.*"as $filename) {  
  3.     echo $filename."<br />";  
  4. }  

  1. // get all text files with the extension .txt  
  2. foreach (glob("*.txt"as $filename) {  
  3.     echo $filename."<br />";  
  4. }  
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