PHP:使用scandir不排除././结果


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>";
        }

问题是,脚本也会回声"."answers".."(没有语音标记),有没有一种优雅的方法可以去除这些?短表达式或正则表达式。感谢

如果目录是...,请继续。我建议查看此处的控制结构

$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的答案之外,另一个解决方案是简单地删除"answers".."在对它们进行迭代之前。

改编自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) {
    // ...
}

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