简体   繁体   English

PHP Scandir返回额外的句点

[英]PHP Scandir returns extra periods

So I am trying to build a script that scans a directory and returns random images to be used as backgrounds. 所以我正在尝试构建一个扫描目录并返回随机图像以用作背景的脚本。

The php looks like this: php看起来像这样:

$dir = "views/img/bg/";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $files[] = $filename;
}

$random_key = array_rand($files, 1);

$random = $files[$random_key];

Then I am just using some simple jquery to attach the images as backgrounds: 然后我只是使用一些简单的jquery将图像作为背景附加:

<script>
$(document).ready(function(){

    $("body").css( "background" , "url(http://'.$url_root.'/views/img/bg/'.$random.'), center center" );

});
</script>

Everything works fine but the array of all the images in the background folder seems to be returning stuff like '.' 一切正常,但背景文件夹中所有图像的数组似乎都返回了像“。”这样的东西。 or '..' instead of image names every once in a while. 或者'..'而不是每隔一段时间的图像名称。 Im not sure what is going on - any ideas? 我不知道发生了什么 - 任何想法?

'.' '' and '..' are returned for current and parent directory. 并为当前和父目录返回'..'。 You can filter them: 你可以过滤它们:

while (false !== ($filename = readdir($dh))) {
    if ($filename != '.' && $filename != '..')    
        $files[] = $filename;
}

Use glob() so you can filter the files. 使用glob()以便过滤文件。

$files = glob('views/img/bg/*.jpg');
$random = $files[array_rand($files)];

Since you're specifying *.jpg , $files contains only JPG files and you don't need to remove the . 由于您指定*.jpg$files仅包含JPG文件,您无需删除. and .. items. ..项目。

Why not use regex? 为什么不使用正则表达式? That way it captures any amount of periods. 这样它可以捕获任何数量的时期。 (ie ".", "..", "..." etc..) (即“。”,“..”,“......”等。)

while (false !== ($filename = readdir($dh))) {
        if(!preg_match('/^\.*$/',$filename)){
            $files[] = $filename;
        }
$dh = opendir("c:\");
while (false !== ($filename = readdir($dh))) {
    if ($filename != '.' && $filename != '..')    
       $files[] = $filename;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM