Iterate through a specific directory tree and stor

2019-06-14 19:13发布

问题:

Lets say I have a lot of files, some of those are in these paths:

root/fonts/folder1/font1.ttf
root/fonts/folder1/font2.ttf
root/fonts/folder2/font1.ttf
root/fonts/folder2/font2.ttf
root/scripts/file.php

Remember that there are also other types of files in those folders. How can my "/scripts/file.php" iterate through the "../fonts/" directory tree and store all the TrueType font (.ttf) files into an array? Could you show me an example?

回答1:

SPL's recursive iterators are particularly useful for this type of functionality:

abstract class FilesystemRegexFilter extends RecursiveRegexIterator {
    protected $regex;
    public function __construct(RecursiveIterator $it, $regex) {
        $this->regex = $regex;
        parent::__construct($it, $regex);
    }
}

class FilenameFilter extends FilesystemRegexFilter {
    // Filter files against the regex
    public function accept() {
        return ( ! $this->isFile() || preg_match($this->regex, $this->getFilename()));
    }
}

class DirnameFilter extends FilesystemRegexFilter {
    // Filter directories against the regex
    public function accept() {
        return ( ! $this->isDir() || preg_match($this->regex, $this->getFilename()));
    }
}

$directory = new RecursiveDirectoryIterator(realpath(__DIR__ . '../fonts'));
$filter = new DirnameFilter($directory, '/^(?!\.)/');
$filter = new FilenameFilter($filter, '/(?:ttf)$/i');

$myArray = [];
foreach(new RecursiveIteratorIterator($filter) as $file) {
    $myArray[] = $file;
}

Though not sure why you need to build an array, and don't simply work with the files inside your foreach loop



回答2:

This may be not the most elegant solution, but I once did the following:

$all_files = scandir("path/to/your/dir");
$selected_files = array();

foreach($all_files as $file)
{
  $tmp = explode(".", $file);
  if($tmp[1] == "ttf") { 
    array_push($selected_files, $file);
  }
}

Now the selected files are stored in selected_files array.

EDIT: Of course, in this solution, your files' names can have only one dot.