2017-08-02 138 views
1

好吧,我一直在尋找一種方式來列出目錄和文件,我已經想通了,和我使用的代碼,我發現這裏StackOverflow上(Listing all the folders subfolders and files in a directory using php)。環繞輸出在正確嵌套列表 - PHP目錄列表

到目前爲止,我已經改變了代碼的答案中的一個發現。我已經能夠從路徑和使用preg_replace文件名都刪除文件擴展名,利用使用ucwords的文件名,並轉出破折號使用str_replace空間。

我遇到了現在是在嚴格嵌套的HTML列表包裹了整個事情鬧什麼。我設法設置它,所以它被包裝在一個列表中,但它不會在需要時使用嵌套列表,在我的生活中,我不能使用目錄名稱的大寫或替換內部的任何破折號目錄名稱。

所以,問題是,如果有人會這麼好心:

  1. 如何包裝在正確的嵌套列表輸出?
  2. 如何利用目錄名,同時消除前斜線和替換破折號或空格下劃線?

我已經將|&nbsp;&nbsp;置於$ss變量內。當我想要輸入字符時,我將它用作各種標記,以確定在試驗和錯誤期間顯示的位置(例如$ss = $ss . "<li>workingOrNot")。

我使用:

<?php 
$pathLen = 0; 

function prePad($level) { 
    $ss = ""; 

    for ($ii = 0; $ii < $level; $ii++) { 
     $ss = $ss . "|&nbsp;&nbsp;"; 
    } 

    return $ss; 
} 

function dirScanner($dir, $level, $rootLen) { 
    global $pathLen; 

    $filesHidden = array(".", "..", '.htaccess', 'resources', 'browserconfig.xml', 'scripts', 'articles'); 

    if ($handle = opendir($dir)) { 

     $fileList = array(); 

     while (false !== ($entry = readdir($handle))) { 
      if ($entry != "." && $entry != ".." && !in_array($entry, $filesHidden)) { 
       if (is_dir($dir . "/" . $entry)) { 
        $fileList[] = "F: " . $dir . "/" . $entry; 
       } 
       else { 
        $fileList[] = "D: " . $dir . "/" . $entry; 
       } 
      } 
     } 
     closedir($handle); 

     natsort($fileList); 

     foreach($fileList as $value) { 
      $displayName = ucwords (str_replace("-", " ", substr(preg_replace('/\\.[^.\\s]{3,5}$/', '', $value), $rootLen + 4))); 

      $filePath = substr($value, 3); 

      $linkPath = str_replace(" ", "%20", substr(preg_replace('/\\.[^.\\s]{3,5}$/', '', $value), $pathLen + 3)); 

      if (is_dir($filePath)) { 
       echo prePad($level) . "<li>" . $linkPath . "</li>\n"; 

       dirScanner($filePath, $level + 1, strlen($filePath)); 

      } else { 
       echo "<li>" . prePad($level) . "<a href=\"" . $linkPath . "\" class=\"className\">" . $displayName . "</a></li>\n"; 
      } 
     } 
    } 
} 

我覺得這些問題的答案應該是簡單的,所以也許我一直盯着它太多的最後兩天也許它已成爲科學怪人的代碼。

我約了試錯的,我需要幫助。

回答

1
foreach($fileList as $value) { 
    $displayName = ucwords (str_replace("-", " ", substr(preg_replace('/\\.[^.\\s]{3,5}$/', '', $value), $rootLen + 4))); 

    $filePath = substr($value, 3); 

    $linkPath = str_replace(" ", "%20", substr(preg_replace('/\\.[^.\\s]{3,5}$/', '', $value), $pathLen + 3)); 

    if (is_dir($filePath)) { 
     // Do not close <li> yet, instead, open an <ul> 
     echo prePad($level) . "<li>" . $linkPath; . "<ul>\n"; 
     dirScanner($filePath, $level + 1, strlen($filePath)); 
     // Close <li> and <ul> 
     echo "</li></ul>\n"; 
    } else { 
     echo "<li>" . prePad($level) . "<a href=\"" . $linkPath . "\" class=\"className\">" . $displayName . "</a></li>\n"; 
    } 
} 

我猜你打開主調用函數之前,並在結束時關閉它。

+0

輝煌。我知道這是我錯過的簡單事情。非常感謝。 – Jaime