Using PHP to Find Files with Name Containing a Wildcard

August 24th, 2011 - Posted by Steve Marks to PHP, Web Development.

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.

Tags:
This entry was posted on Wednesday, August 24th, 2011 at 7:21 pm by +Steve Marks and is filed under PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (2)
  1. Tuymurod says:

    Thank.. I’ve been looking for this solution for hours.

  2. Ivan says:

    Thank.. I’ve been looking for this solution for hours.