我想使用opendir()仅列出特定文件夹中的文件夹(即/ www/site /).我想从列表中排除文件以及'.' 以及出现在linux文件夹列表中的'..'文件夹.我该怎么做呢?
Jas*_*ary 18
查看readdir()的PHP文档.它包含了一个这样的例子.
为了完整性:
<?php
if ($handle = opendir('.')) {
$blacklist = array('.', '..', 'somedir', 'somefile.php');
while (false !== ($file = readdir($handle))) {
if (!in_array($file, $blacklist)) {
echo "$file\n";
}
}
closedir($handle);
}
?>
Run Code Online (Sandbox Code Playgroud)
只需更改opendir('.')到您的目录,即opendir('/www/sites/')更新$blacklist以包含您不希望输出的文件或目录的名称.
Sta*_*eyD 18
foreach(glob('directory/*', GLOB_ONLYDIR) as $dir) {
$dir = str_replace('directory/', '', $dir);
echo $dir;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用GLOB_ONLYDIR简单地使用glob,然后过滤生成的目录
function scandir_nofolders($d) {
return array_filter(scandir($d), function ($f) use($d) {
return ! is_dir($d . DIRECTORY_SEPARATOR . $f);
});
}
Run Code Online (Sandbox Code Playgroud)
这个函数返回一个你可以迭代或存储在某个地方的数组,这是99.37%的所有程序员都opendir想要的.
仅列出文件夹(目录):
<?php
$Mydir = ''; ### OR MAKE IT 'yourdirectory/';
foreach(glob($Mydir.'*', GLOB_ONLYDIR) as $dir) {
$dir = str_replace($Mydir, '', $dir);
echo $dir;
}
?>
Run Code Online (Sandbox Code Playgroud)