dongyan5641 2013-07-25 17:40
浏览 105
已采纳

如何使此查找特定扩展名并仅显示文件名

1) how can i make this read only ".txt" files

2) how can i make it show only the file name so i can design it how i'd i like.. (<h1>$file</h1> for example)

$dir = "includes/news";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh)))
{
    if ($filename != "." && $filename != ".." && strtolower(substr($filename, strrpos($filename, '.') + 1)) == 'txt')
    {
    $files[] = $filename;
    }
}
sort($files);
echo $files;

what it shows right now is:

Array ( [0] => . [1] => .. [2] => [23.7] Hey.txt [3] => [24.7] New Website.txt [4] => [25.7] Example.txt )

Now, this is another way i could do it, i like it bit better:

        if( $handle = opendir( 'includes/news' )) 
    {
        while( $file = readdir( $handle )) 
        {
            if( strstr( $file, "txt" ) )
            {
                $addr = strtr($file, array('.txt' => ''));
                echo '<h1><a href="?module=news&read=' . $addr . '">&raquo; ' . $addr . "</a></h1>";
            }
         }
        closedir($handle);
    }

but the my issue with this one is that there is no Sorting between the files. everything is ok with the output, just the order of them. so if one of you can figure out how to sort them right, that would be perfect

  • 写回答

3条回答 默认 最新

  • dtz30833 2013-07-25 18:14
    关注

    Okay, try this:

    $files = array();
    if($handle = opendir( 'includes/news' )) {
        while( $file = readdir( $handle )) {
            if ($file != '.' && $file != '..') {
                // let's check for txt extension
                $extension = substr($file, -3);
                // filename without '.txt'
                $filename = substr($file, 0, -4);
                if ($extension == 'txt')
                    $files[] = $file; // or $filename
            }
        }
        closedir($handle);
    }
    sort($files);
    foreach ($files as $file)
        echo '<h1><a href="?module=news&read=' . $file 
            . '">&raquo; ' . $file . "</a></h1>";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探