Getting certain files from a directory

Friday, 27 June 2008


Recently while reading the book Professional LAMP: Linux, Apache, MySQL, and PHP5 Web Development I came across a great piece code that can be used to retrieve an array of filenames from a directory matching a certain pattern. Unfortunately the function in the book doesn't quite work with the current definition of that function, but with a bit of tweeking we can get it to do the same thing.

Previously we would use preg_grep along with scandir to match the files in a directory to a certain pattern. As follows:

$files = preg_grep('/\.php$/', scandir('./'));

Using the glob() function we can now easily search for a variety of file types. With the glob() function we have a bunch of flags, the one we are interested in is GLOB_BRACE which will allow us to search for more than one type of file extension.

Our function call will incorporate the directory we want to search in, the file types we want to search for and our GLOB_BRACE flag.

Our directory: "./"
Our file types: "{*.jpg,*.gif,*.png}"
Our flag: "GLOB_BRACE"

Put it all together and we get the following call:

$filelist = glob('./{*.jpg,*.gif,*.png}', GLOB_BRACE);


And the result when we print it out:


Array
(
[0] => ./library.jpg
[1] => ./hi.jpg
[2] => ./test.png
)



Sweet!
blog comments powered by Disqus