简体   繁体   English

PHP scandir()但不包括某些文件夹

[英]PHP scandir() but exclude certain folders

I found this function below here on stackoverflow however, I am trying to avoid scanning any directory with the name includes. 我在下面的stackoverflow上找到了此函数,但是,我试图避免扫描名称为includes.任何目录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;
}

I have tried adding an additional && as follows: 我尝试添加其他&& ,如下所示:

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

However, this does not seem to be doing the trick. 但是,这似乎并没有解决问题。

只需删除斜杠:

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

I am trying to avoid scanning any directory with the name "includes". 我试图避免扫描名称为“ includes”的任何目录。

You could try replacing 您可以尝试更换

$files = scandir($dir);

with

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

This will result in an array of $files which do not contain the string "includes" using preg_grep and inverted matching. 这将导致$files数组使用preg_grep和反向匹配不包含字符串“ includes”。

If set to PREG_GREP_INVERT, this function returns the elements of the input array that do not match the given pattern ( ref ). 如果设置为PREG_GREP_INVERT,则此函数返回输入数组中与给定模式( ref )不匹配的元素。

As a bonus, you can easily customize the regular expression to add more excluded paths. 另外,您可以轻松自定义正则表达式以添加更多排除的路径。 Example: 例:

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

This will also exclude directories that start with a . 这还将排除以.开头的目录. , so you can reduce some of your logic. ,因此您可以减少一些逻辑。


An alternative is 替代方法是

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

This will result in an array of $files which do not contain the string "includes". 这将导致不包含字符串“ includes”的$files数组。 It uses preg_grep and negative look-arounds to check for "includes", and if not found, that path is included in the final array. 它使用preg_grep否定环顾 四周来检查“ includes”,如果找不到,则该路径将包含在最终数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM