2013-07-25 25 views
1

1)我怎樣才能使這個只讀名爲「.txt」文件如何使這一發現特定的擴展,僅顯示文件名

2)我如何使它只顯示文件名,這樣我就可以設計怎麼我會我喜歡.. (<h1>$file</h1>例如)

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

它右邊顯示的是現在:

Array ([0] => . [1] => .. [2] => [23.7] Hey.txt [3] => [24.7] New 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); 
    } 

但我的問題是這個文件之間沒有排序。 一切都可以與輸出,只是他們的順序。所以如果你們其中一個可以弄清楚如何對它們進行正確分類,那將是完美的

+0

讓我們看看你已經嘗試了一些代碼。我敢打賭,你有一些 –

+0

我增加了另一種方式,我嘗試了它,它在底部。你能否檢查它:) – user2617739

回答

0

好了,試試這個:

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

這裏的排序很好!它的工作原理,它顯示了我所需要的。但問題是這是顛倒了,我可以改變排序rsort?另外,.txt擴展名仍然存在。它顯示[23.7] Hey.txt – user2617739

+0

如果你想使用'rsort'。當我在註釋中寫入時,將'$ filename'而不是'$ file'放在'$ file'中。 –

+0

完美。非常感謝 ! – user2617739

0

我認爲這應該能夠完成你想要做的事情。它使用爆炸和負面限制來查找僅.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>'; 

} 
+0

爲什麼這是downvoted? –

+0

謝謝,而不是我的壽。好的,所以我試了一下,我添加了$ dh =「includes/news」;這是文件夾,但我得到的錯誤是解析錯誤:語法錯誤,意外'[' – user2617739

+0

你應該使用你的原始位代碼(見編輯) –

0

試圖使它儘可能簡單 嘗試這個

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); 
} 
相關問題