PHP Directories Getting a List of Filenames Matching a Pattern - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Directories Getting a List of Filenames Matching a Pattern - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Monday, July 15, 2019

PHP Directories Getting a List of Filenames Matching a Pattern

PHP Directories


Getting a List of Filenames Matching a Pattern

Problem

You want to find all filenames that match a pattern.

Solution

Use a FilterIterator subclass with DirectoryIterator. The FilterIterator subclass needs its own accept() method that decides whether or not a particular value isacceptable.

To only accept filenames that end with common extensions for images:

       class ImageFilter extends FilterIterator {
              public function accept() {
                     return preg_match('@\.(gif|jpe?g|png)$@i',$this->current());
              }
       }
       foreach (new ImageFilter(new DirectoryIterator('/usr/local/images')) as $img) {
              print "<img src='".htmlentities($img)."'/>\n";
       }

Discussion

The FilterIterator encloses a DirectoryIterator and only allows certain elements to emerge. It’s up to the accept() method to return true or false to indicate whether a particular element (accessed with $this->current()) is OK. In the Solution, accept() uses a regular expression to make that determination, but your code can use any logic you like.

If your pattern can be expressed as a simple shell glob (e.g., *.*), use the glob() function to get the matching filenames. For example, to find all the text files in a particular directory:

       foreach (glob('/usr/local/docs/*.txt') as $file) {
              $contents = file_get_contents($file);
              print "$file contains $contents\n";
       }

The glob() function returns an array of matching full pathnames. If no files match the pattern, glob() returns false.

No comments:

Post a Comment

Post Top Ad