19.8. Getting a List of Filenames Matching a Pattern

Problem

You want to find all filenames that match a pattern.

Solution

If your pattern is a regular expression, read each file from the directory and test the name with preg_match( ) :

$d = dir('/tmp') or die($php_errormsg);
while (false !== ($f = $d->read())) {
    // only match alphabetic names
    if (preg_match('/^[a-zA-Z]+$/',$f)) {
        print "$f\n";
    }
}
$d->close();

Discussion

If your pattern is a shell glob (e.g., *.*), use the backtick operator with ls (Unix) or dir (Windows) to get the matching filenames. For Unix:

$files = explode("\n",`ls -1 *.gif`);
foreach ($files as $file) {
  print "$b\n";
}

For Windows:

$files = explode("\n",`dir /b *.gif`);
foreach ($files as $file) {
  print "$b\n";
}

See Also

Recipe 19.8 details on iterating through each file in a directory; information about shell pattern matching is available at http://www.gnu.org/manual/bash/html_node/bashref_35.html.

Get PHP Cookbook 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.