File search and wildcards in PHP

Posted by Stanislav Furman  on June 7, 2013

This post will continue one of my previous posts Reading file list from a mapped Windows network drive.

Recently, I have had a challenge with reading files from a directory using a wildcard pattern (i.e. " *.jpg "). Obviously, regular is_file() or file_exists() functions do not work in this case. So, I started looking for a solution that could help me with my problem.

Luckily, there is a function glob() that searches for the pathnames matching given pattern.


<?php
foreach(glob('*.jpg') as $image) {
  if( !is_dir($image) ) {
    $images[] = $image;
  }
}
?>

In addition, as of PHP >= 5.3, you could use the new GlobIterator.


<?php
$iterator = new GlobIterator('*.jpg', FilesystemIterator::KEY_AS_FILENAME);

if (!$iterator->count()) {
    echo 'No images found';
} else {
    $n = 0;

    printf("Matched %d item(s)\r\n", $iterator->count());

    foreach ($iterator as $item) {
        printf("[%d] %s\r\n", ++$n, $iterator->key());
    }
}
?>

Hoping that now this will help you when it comes to searching files with a pattern. Good luck!


Leave your comment

Fields with * are required.

* When you submit a comment, you agree with Terms and Conditions of Use.