根据特定模式重新获取文件

时间:2017-09-10 21:46:35

标签: php codeigniter

我正在使用此功能从目录和子目录中检索文件。 如何在此目录和子目录中仅显示带有_lang.php的文件?

function getDirContents($dir, &$results = array()){
    $files = scandir($dir);

    foreach($files as $key => $value){
        $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
        if(!is_dir($path)) {
            $results[] = $path;
        } else if($value != "." && $value != "..") {
            getDirContents($path, $results);
            $results[] = $path;
        }
    }

    return $results;
}
$dir = './test/';
var_dump(getDirContents($dir));

1 个答案:

答案 0 :(得分:2)

回答了类似earlier之类的问题,请尝试使用Iterator

<?php
function getDirContents($directory, $pattern)
{
    $result = array();
    $objRecursiveDirectoryIterator = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS);
    $objRecursiveIteratorIterator = new RecursiveIteratorIterator($objRecursiveDirectoryIterator);
    // use RegexIterator() to grab only files that match $pattern
    $objRegexIterator = new RegexIterator($objRecursiveIteratorIterator, $pattern, RecursiveRegexIterator::GET_MATCH);

    // iterate through all the results
    foreach ($objRegexIterator as $arrMatches) {
       $result[] = $arrMatches[0];
    }
    return $result;
}

$dir = './test/';
$arrDirContents = getDirContents($dir, "~^.+_lang\.php$~i");
var_dump($arrDirContents);