从文件夹中读取文件名仅保留扩展名为.iso的文件

时间:2011-03-29 19:36:53

标签: php

我有一个脚本从配置文件中获取一个字符串,并根据该字符串获取文件夹的文件名。

我现在只需要iso文件。不确定最好的方法是检查.iso字符串还是有另一种方法?

<?php
    // Grab the contents of the "current.conf" file, removing any linebreaks.
    $dirPath = trim(file_get_contents('current.conf')).'/';

    $fileList = scandir($dirPath);

    if(is_array($fileList)) {
        foreach($fileList as $file) {
//could replace the below if statement to only proceed if the .iso string is present. But I am worried there could be issues with this.


         if ($file != "." and $file != ".." and $file != "index.php")
{

            echo "<br/><a href='". $dirPath.$file."'>" .$file."</a>\n";
    }
        } 
    }
    else echo $dirPath.' cound not be scanned.';
?>

3 个答案:

答案 0 :(得分:4)

如果您只需要扩展名为.iso的文件,那么为什么不使用:

glob($dirPath.'/*.iso');

而不是scandir()

答案 1 :(得分:0)

试试这个:

    if(is_array($fileList)) {
        foreach($fileList as $file) {

            $fileSplode = explode('.',$file); //split by '.'
            //this means that u now have an array with the 1st element being the
            //filename and the 2nd being the extension

            echo (isset($fileSplode[1]) && $fileSplode[1]=='iso')?
                    "<br/><a href='". $dirPath.$file."'>" .$file."</a>\n":'');
        } 
    }

答案 2 :(得分:0)

如果你想要它采用OOP风格,你可以使用:

<?php

foreach (new DirectoryIterator($dirPath) as $fileInfo) {
   if($fileInfo->getExtension() == 'iso') {
      // do something with it
   }
}

?>