hi I'm writing a script to loop through the current directory and list all sub directories all is working fine but i can't get it to exclude folders starting with an _
<?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);
}
}
?>
you can use substr
[docs] like :
|| substr($file, 0, 1) === '_'
No need for a regex, use $file[0] == '_'
or substr($file, 0, 1) == '_'
If you do want a regex, you need to use preg_match()
to check: preg_match('/^_/', $file)
Or, if you would like to use regexp, you should use regex functions, like preg_match: preg_match('/^_/', $file)
; but as said by ThiefMaster, in this case a $file[0] == '_'
suffices.
A more elegant solution is to use SPL. The GlobIterator can help you out. Each item is an instance of SplFileInfo.
<?php
$dir = __DIR__ . '/[^_]*';
$iterator = new GlobIterator($dir, FilesystemIterator::SKIP_DOTS);
if (0 < $iterator->count()) {
echo "<ul>
";
foreach ($iterator as $item) {
if ($item->isDir()) {
echo sprintf("<li>%s</li>
", $item);
}
}
echo "</ul>
";
}