0

具有以下内容以在数组中提供目录列表

for($index=0; $index < $indexCount; $index++) {
        if (substr("$dirArray[$index]", 0, 1) != ".") { // don't list hidden files
 echo "<option value=\"".$dirArray[$index]."\">".$dirArray[$index]."</option>";
 }

有什么办法可以修改上面的代码,只显示 .JPG 和 .PNG 吗?

谢谢!

CP

4

3 回答 3

2
foreach($dirArray[$index] as $k => $v) {
     if(in_array(pathinfo($v, PATHINFO_EXTENSION), array('jpg', 'png', 'jpeg')) {
         echo '<option value="'.$v.'">'.$v.'</option>';
     }
}

我假设有关您的文件数组的一些事情。还有你不使用 readdir() 函数的原因吗?

于 2013-07-11T15:53:58.073 回答
1

You can use regular expression to match if file name ends with .jpg or .png

for($index=0; $index < $indexCount; $index++) 
{
    if(preg_match("/^.*\.(jpg|png)$/i", $dirArray[$index]) == 1) 
    {
      echo "<option value=\"".$dirArray[$index]."\">".$dirArray[$index]."</option>";
    }
}

/i at the end of regular expression is case insensitive flag.

于 2013-07-11T15:27:49.843 回答
0
for($index=0; $index < $indexCount; $index++) {
        if (substr($dirArray[$index], 0, 1) != "." 
            && strtolower(substr($dirArray[$index], -3)) == 'png' 
            && strtolower(substr($dirArray[$index], -3)) == 'jpg')
            echo '<option value="'.$dirArray[$index].'">'.$dirArray[$index].'</option>';
 }

这应该可行,但有更优雅的解决方案,比如使用DirectoryIterator(见这里):

foreach (new DirectoryIterator('your_directory') as $fileInfo) {
    if($fileInfo->isDot() 
        || !in_array($fileInfo->getExtension(), array('png', 'jpg'))) 
        continue;
    echo sprintf('<option value="%s">%s</option>', 
        $fileInfo->getFilename(), 
        $fileInfo->getFilename());
}

代码未经测试,您可能需要对其进行一些修改。

于 2013-07-11T15:42:16.407 回答