I am writing a simple fishing game in PHP. I have a snippet of code that's printing all of the image files in my /img directory, but it's also outputting .DS_Store. I want to exclude that file, maybe using glob(), but I don't know how. I've googled this for hours with no luck.

$files = scandir('img');
if ($files !== false) {
    foreach($files as $f) {
        if ($f == '..' || $f == '.') continue;
            echo '<li class="fish_pic"><img src="img/'.$f.'" alt="'.$f.'" title="" class="fish"></li>'."\n";
    }
}

How can I exclude .DS_Store?

有帮助吗?

解决方案 2

$files = scandir('img');
if ($files !== false) {
    foreach($files as $f) {
        if ($f == '..' || $f == '.' || substr($f, -strlen(".DS_Store")) === ".DS_Store") continue;
            echo '<li class="fish_pic"><img src="img/'.$f.'" alt="'.$f.'" title="" class="fish"></li>'."\n";
    }
}

其他提示

Just add an if rule.

if ($f == '..' || $f == '.' || $f == '.DS_Store') continue;

Alternatively, you could use an array and in_array() method.

$filesToSkip = array('.', '..', '.DS_Store', 'other_file_to_skip');

$files = scandir('img');
if ($files !== false) {
 foreach($files as $f) {
   if (in_array($f, $filesToSkip)) continue;
   echo '<li class="fish_pic"><img src="img/'.$f.'" alt="'.$f.'" title="" class="fish">   </li>'."\n";
 }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top