[英]PHP: Using scandir bu excluding ../ ./ in the result
I'm using scandir and a foreach loop to display a list of files in a directory to the user. 我正在使用scandir和foreach循环来向用户显示目录中的文件列表。 My code is below:
我的代码如下:
$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>";
}
The problem is the script also echos a "." 问题是剧本也回应了“。” and a ".." (without the speech marks), is there an elegant way to remove these?
和一个“..”(没有语音标记),是否有一种优雅的方式来删除这些? Short or a regular expression.
短或正则表达式。 Thanks
谢谢
Just 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>";
}
Instead of this: 而不是这个:
if( $directory == '.' || $directory == '..' ) {
// directory is . or ..
// continue will directly move on with the next value in $directory
continue;
}
you can use a short version of it: 你可以使用它的简短版本:
if( $directory == '.' || $directory == '..' ) continue;
You can eliminate these directories with array_diff
: 您可以使用
array_diff
消除这些目录:
$dir = scandir($path);
$dir = array_diff($dir, array('.', '..'));
foreach($dir as $entry) {
// ...
}
Another solution, in addition to swidmann's answer, is to simply remove '.' 除了swidmann的答案之外,另一个解决方案是简单地删除'。' and '..' before iterating over them.
和迭代之前的'..'。
Adapted from http://php.net/manual/en/function.scandir.php#107215 改编自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) {
// ...
}
That way you can also easily add other directories and files to the excluded list should the need arise in the future. 这样,如果将来需要,您还可以轻松地将其他目录和文件添加到排除列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.