3.2. glob()

A task you may often find yourself doing is reading through a directory for files with names matching a certain pattern—all the text files, for example, or image files. This can be simpler than storing the files in the filesystem, maintaining a list of those files elsewhere, and then having to keep the two synchronized. And it's possible that other types of files are in the same directory. This is such a common task that any shell interface provides "globbing"—you can list *.png, delete temp_*, and so forth. Prior to PHP 4.3, the typical method of achieving the same effect would have used readdir() and, based on the examples of that function's use given in the manual, ended up with something that looks like this:

$filelist = array();
if ($handle = opendir('directory'))
{
    while (false !== ($file = readdir($handle)))
    {
        if(substr($file, −4)=='.txt')
        {
            $filelist[] = $file;
        }
    }
    closedir($handle);
}

PHP 5 introduces scandir(), which encapsulates the whole opendir()/readdir()/loop()/closedir() business, leaving the job of filtering the filenames until afterwards, which in this example could be handled by preg_grep() like this:

$filelist = preg_grep('/\.txt$/', scandir('directory'));

But since PHP 4.3, even this is unnecessarily complicated. By using the same shell-like globbing syntax, where ? represents "any single character" and * represents "any string," you can use the same syntax that you use in the shell to do the same filtering of file names.$filelist = glob('*.txt', ...

Get Professional LAMP: Linux®, Apache, MySQL®, and PHP5 Web Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.