遍历特定目录树并将所有 .ttf 文件存储到 PHP 中的数组中

Iterate through a specific directory tree and store all the .ttf files into an array in PHP

假设我有很多文件,其中一些在这些路径中:

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

请记住,这些文件夹中还有其他类型的文件。我的 "/scripts/file.php" 如何遍历 "../fonts/" 目录树并存储将所有 TrueType 字体 (.ttf) 文件放入一个数组中?你能举个例子吗?

SPL 的递归迭代器对此类功能特别有用:

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;
}

虽然不确定为什么需要构建数组,但不要简单地使用 foreach 循环中的文件

这可能不是最优雅的解决方案,但我曾经这样做过:

$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);
  }
}

现在所选文件存储在 selected_files 数组中。

编辑: 当然,在此解决方案中,您的文件名只能有一个点。