PHP: 在结果中使用 scandir bu 排除 ../ ./

PHP: Using scandir bu excluding ../ ./ in the result

我正在使用 scandir 和 foreach 循环向用户显示目录中的文件列表。我的代码如下:

        $dir = scandir('/user1/caravans/public_html/wordpress/wp-content/uploads/wpallimport/files');

        foreach($dir as $directory)
{
        echo "<br/><input type='checkbox' name=\"File[]\" value='$directory'/>$directory<br>";
        }

问题是脚本还回显了“.”。和一个“..”(没有语音标记),有没有一种优雅的方法可以删除这些?简短或正则表达式。谢谢

continue if the directory is . or .. I recommend to take a look at the control structures here

$dir = scandir('/user1/caravans/public_html/wordpress/wp-content/uploads/wpallimport/files');

foreach($dir as $directory) {
    if( $directory == '.' || $directory == '..' ) {
        // directory is . or ..
        // continue will directly move on with the next value in $directory
        continue;
    }

    echo "<br/><input type='checkbox' name=\"File[]\" value='$directory'/>$directory<br>";
}

而不是这个:

if( $directory == '.' || $directory == '..' ) {
    // directory is . or ..
    // continue will directly move on with the next value in $directory
    continue;
}

你可以使用它的简短版本:

if( $directory == '.' || $directory == '..' ) continue;

您可以使用 array_diff:

删除这些目录
$dir = scandir($path);
$dir = array_diff($dir, array('.', '..'));
foreach($dir as $entry) {
    // ...
}

除了 swidmann 的回答之外,另一种解决方案是简单地删除“.”。和 '..' 在遍历它们之前。

改编自http://php.net/manual/en/function.scandir.php#107215

$path    = '/user1/caravans/public_html/wordpress/wp-content/uploads/wpallimport/files';
$exclude = ['.', '..'];
$dir     = array_diff(scandir($path), $exclude);

foreach ($dir as $directory) {
    // ...
}

这样您还可以在将来需要时轻松地将其他目录和文件添加到排除列表中。