Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata