File And Directory Manipulation In PHP (part 2) - A Pattern Emerges (Page 9 of 13 )
Want to list just the files matching a specific pattern? Use the neat little fnmatch() function, new in PHP 4.3, which matches strings against wildcard patterns. Here's a quick example:
<?php
// set directory name
$dir = "/bin";
// set pattern
$pattern = "e*";
// open directory and parse file list
if (is_dir($dir))
{
if ($dh = opendir($dir))
{
// iterate over file list
while (($filename = readdir($dh)) !== false)
{
// if filename matches search pattern, print it
if (fnmatch($pattern, $filename))
{
echo $dir . "/" . $filename . "\n";
}
}
// close directory
closedir($dh);
}
}
?>
Here's an example of the output:
/bin/ed
/bin/egrep
/bin/echo
/bin/env
/bin/ex
The * wildcard matches one or more characters; if this is not what you want, you can also use the ? wildcard to match a single character.
An alternative to using fnmatch() with the opendir() and readdir() functions is the glob() function, also new to PHP 4.3 - this function searches the current directory for files matching the specified pattern and returns them as an array. Consider the following rewrite of the example above, which demonstrates:
<?php
// set directory name
$dir = "/bin";
// set pattern
$pattern = "e*";
// change to named directory
chdir($dir);
// find files matching pattern
$files = glob($pattern);
// iterate over files array and print filenames
foreach ($files as $f)
{
echo $dir . "/" . $f . "\r\n";
}
?>
Since glob() looks in the current directory for files, remember to always
chdir() to the correct directory before executing glob().
Next: Purging The Dead >>
More PHP Articles
More By icarus, (c) Melonfire