嗨,我正在编写一个脚本来循环当前目录并列出所有子目录一切正常,但我无法让它排除以 _ 开头的文件夹
<?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);
}
}
?>
您可以使用substr
[docs],例如:
|| substr($file, 0, 1) === '_'
不需要正则表达式,使用 $file[0] == '_'
或 substr($file, 0, 1) == '_'
如果你确实想要一个正则表达式,你需要使用preg_match()
来检查:preg_match('/^_/', $file)
或者
,如果你想使用正则表达式,你应该使用正则表达式函数,如preg_match:preg_match('/^_/', $file)
; 但正如 ThiefMaster 所说,在这种情况下,$file[0] == '_'
就足够了。
更优雅的解决方案是使用 SPL。GlobIterator可以帮助您。每个项目都是 SplFileInformation 的一个实例。
<?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";
}