0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

php 特定ディレクトリ内のファイル名一覧を取得

Posted at

php 特定ディレクトリ内のファイル名一覧を取得

指定ディレクトリからファイル名一覧を抜き出します。

下記イテレーターを使用してディレクトリ配下のファイル名を取得していきます。
http://php.net/manual/ja/class.recursivedirectoryiterator.php (RecursiveDirectoryIterator クラス)
http://php.net/manual/ja/class.recursiveiteratoriterator.php (RecursiveIteratorIterator クラス)

getFileList
public function getFileList($dir) {
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
    $list = [];
    foreach ($iterator as $fileinfo) {
        if ($fileinfo->isFile()) 
            $list[] = $fileinfo->getPathname();
    return $list;
}

処理内の[$fileinfo]はSplFiIeInfoオブジェクトとなります。
isFile()にてファイル確認をしています。
http://php.net/manual/ja/class.splfileinfo.php (SplFileInfo クラス)

php 特定ディレクトリ内のファイル名一覧を取得(正規表現)

下記は正規表現でのパターン条件を追加したversion。

getFileListRegex
public function getFileListRegex($dir, $regex) {
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
    $iterator = new RegexIterator($iterator, $regex, RecursiveRegexIterator::MATCH);
    $list = [];
    foreach ($iterator as $fileinfo) {
        if ($fileinfo->isFile()) 
            $list[] = $fileinfo->getPathname();
    return $list;
}
getFileListRegex(数字4桁のディレクトリから始まるディレクトリを検索使用例)
$dir = dirname(__FILE__);
$regex = sprintf('/^%s[0-9]{4}\/.*$/', preg_quote($dir, '/'));
$files = $file->getFileListRegex($dir, $regex);

RegexIteratorの操作モード(第三引数)は下記
http://php.net/manual/ja/class.regexiterator.php (RegexIterator クラス)

RegexIterator::ALL_MATCHES
現在のエントリにマッチするものをすべて返します (preg_match_all() を参照ください)。

RegexIterator::GET_MATCH
現在のエントリに最初にマッチしたものを返します (preg_match() を参照ください)。

RegexIterator::MATCH
現在のエントリに対するマッチ (フィルタ) のみを行います (preg_match() を参照ください)。

RegexIterator::REPLACE
現在のエントリを置換します (preg_replace() を参照ください。まだ完全には実装されていません)。

RegexIterator::SPLIT
現在のエントリで分割した値を返します (preg_split() を参照ください)。

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?