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

Php 如何使其查找特定扩展名并仅显示文件名,php,Php,1如何使此文件成为只读.txt文件 2如何使其仅显示文件名,以便我可以按照自己的喜好进行设计。。 例如$file $dir = "includes/news"; $dh = opendir($dir); while (false !== ($filename = readdir($dh))) { if ($filename != "." && $filename != ".." && strtolower(substr($filename, strrpos

1如何使此文件成为只读.txt文件

2如何使其仅显示文件名,以便我可以按照自己的喜好进行设计。。 例如$file

$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;
它现在显示的是:

数组[0]=>。[1] => .. [2] =>[23.7]Hey.txt[3]=>[24.7]新 Website.txt[4]=>[25.7]Example.txt

现在,这是我可以做的另一种方式,我更喜欢它:

        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);
    }
但我的问题是,这两个文件之间没有排序。
输出一切正常,只是顺序而已。所以,如果你们中的一位能够想出如何正确地对它们进行排序,那将是完美的,我认为这将完成您想要做的事情。它使用explode和负数限制只查找.txt文件,并且只返回名称

$dir = "includes/news";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))){

    $fileName = explode('.txt', $node, -1)[0];
    if(count($fileName) )
        $files[] = '<h1>'.$fileName.'</h1>';

}
好的,试试这个:

$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>";

尽量使它简单 试试这个


向我们展示一些您已经尝试过的代码。我敢打赌你一定有什么我加了另一种方法我试着这么做,它在底部。请你核对一下好吗:谢谢,不是我的。好的,我试过了,我添加了$dh=includes/news;这是文件夹,但我得到的错误是Parse error:syntax error,意外的“[”数组解引用从php5.4开始就可用。这里的排序很好!它可以工作,并且它正好显示了我需要的内容。但问题是它是相反的,我可以将sort更改为rsort吗?另外,.txt扩展名仍然存在。它显示了[23.7]Hey.txtUse rsort,如果需要的话。并将$filename而不是$file放在$files中,正如我在注释中所写的那样。
function check_txt($file){
 $array = explode(".","$file");
 if(count($array)!=1 && $array[count($array)-1]=="txt"){return true;}
 return false;
  }
if($handle = opendir( 'includes/news' )) {
 while( $file = readdir( $handle )) 
    {
        if( check_txt($file) )
        {
            echo '<h1><a href="?module=news&read=' . $file . '">&raquo; ' . $file . "</a></h1>";
        }
     }
    closedir($handle);
}