2012-05-08 31 views
1

嗨,我是通過當前目錄編寫腳本來循環並列出所有子目錄 所有工作正常,但我不能把它排除開頭的文件夾_正則表達式的文件夾開始_

<?php 

$dir = __dir__; 

// Open a known directory, and proceed to read its contents 
if (is_dir($dir)) { 
    if ($dh = opendir($dir)) { 
     echo("<ul>"); 
    while (($file = readdir($dh)) !== false) { 
     if ($file == '.' || $file == '..' || $file == '^[_]*$') continue; 
     if (is_dir($file)) { 
      echo "<li> <a href='$file'>$file</a></li>"; 
     } 
    } 
    closedir($dh); 
} 
} 
?> 

回答

3

你可以使用substr[docs],如:

|| substr($file, 0, 1) === '_' 
+1

完美得益於不會讓我打勾但你回答得太快 –

+0

@MitchellBray:雖然兩個答案都完全沒有問題,可以考慮在尋找答案的時間戳。 – ThiefMaster

3

無需正則表達式,使用$file[0] == '_'substr($file, 0, 1) == '_'

如果想要一個正則表達式,你需要使用preg_match()檢查:preg_match('/^_/', $file)

0

或者,如果你想使用正則表達式,你應該使用正則表達式的功能,如的preg_match:preg_match('/^_/', $file);但正如ThiefMaster所說,在這種情況下,$file[0] == '_'就足夠了。

0

更優雅的解決方案是使用SPLGlobIterator可以幫助你。每個項目都是SplFileInfo的實例。

<?php 

$dir = __DIR__ . '/[^_]*'; 
$iterator = new GlobIterator($dir, FilesystemIterator::SKIP_DOTS); 

if (0 < $iterator->count()) { 
    echo "<ul>\n"; 
    foreach ($iterator as $item) { 
     if ($item->isDir()) { 
      echo sprintf("<li>%s</li>\n", $item); 
     } 
    } 
    echo "</ul>\n"; 
}