我使用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>";
}问题是脚本也呼应了一个“。还有一个“.”(没有语音标记),是否有一个优雅的方法来删除这些?短表达式或正则表达式。谢谢
发布于 2015-11-12 10:31:37
只要继续,如果目录是.或..,我建议查看控件结构这里
$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;发布于 2015-11-12 10:42:12
您可以使用array_diff消除这些目录。
$dir = scandir($path);
$dir = array_diff($dir, array('.', '..'));
foreach($dir as $entry) {
// ...
}发布于 2015-11-12 10:43:56
除了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) {
// ...
}这样,如果将来需要的话,还可以轻松地将其他目录和文件添加到排除的列表中。
https://stackoverflow.com/questions/33669246
复制相似问题