[英]PHP scandir() but exclude certain folders
我在下面的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;
}
我尝试添加其他&&
,如下所示:
} else if (is_dir($path) && $value != "." && $value != ".." && !strstr($path,"includes/")) {
但是,这似乎并没有解决问题。
只需删除斜杠:
!strstr($path,"includes")) {
我试图避免扫描名称为“ includes”的任何目录。
您可以尝试更换
$files = scandir($dir);
同
$files = preg_grep("/includes/i", scandir($dir), PREG_GREP_INVERT);
这将导致$files
数组使用preg_grep和反向匹配不包含字符串“ includes”。
如果设置为PREG_GREP_INVERT,则此函数返回输入数组中与给定模式( ref )不匹配的元素。
另外,您可以轻松自定义正则表达式以添加更多排除的路径。 例:
"/includes|admin|hidden|temp|cache|^\./i"
这还将排除以.
开头的目录.
,因此您可以减少一些逻辑。
替代方法是
$files = preg_grep('/^((?!includes).)*$/i', scandir($dir));
这将导致不包含字符串“ includes”的$files
数组。 它使用preg_grep和否定环顾 四周来检查“ includes”,如果找不到,则该路径将包含在最终数组中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.