PHP scandir()但排除某些文件夹

时间:2015-06-08 01:39:54

标签: php scandir

我在stackoverflow上找到了这个函数,但是我试图避免扫描任何名为includes.的目录

$dir = $_SESSION['site'];
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 (is_dir($path) && $value != "." && $value != ".." ) { 
            getDirContents($path, $results);
            $results[] = $path;
        }
    }
    return $results;
}

我尝试添加额外的&&,如下所示:

} else if (is_dir($path) && $value != "." && $value != ".." && !strstr($path,"includes/")) {

然而,这似乎并没有成功。

2 个答案:

答案 0 :(得分:1)

只需删除尾部斜杠:

!strstr($path,"includes")) {

答案 1 :(得分:0)

  

我试图避免使用名称" includes"。

扫描任何目录

您可以尝试替换

$files = scandir($dir);

$files = preg_grep("/includes/i", scandir($dir), PREG_GREP_INVERT);

这将导致数组$files不包含字符串"包含"使用preg_grep和反向匹配。

  

如果设置为PREG_GREP_INVERT,则此函数返回与给定模式(ref)不匹配的输入数组元素。

作为奖励,您可以轻松自定义正则表达式以添加更多排除的路径。例如:

"/includes|admin|hidden|temp|cache|^\./i"

这也将排除以.开头的目录,因此您可以减少一些逻辑。

另一种选择是

$files = preg_grep('/^((?!includes).)*$/i', scandir($dir));

这将导致数组$files不包含字符串"包含"。它使用preg_grepnegative look-arounds来检查"包含",如果没有找到,则该路径包含在最终数组中。

相关问题