正则表达式以_开头的文件夹

时间:2012-05-08 06:26:50

标签: php regex

嗨,我正在编写一个脚本来遍历当前目录并列出所有子目录 一切正常,但我不能让它排除以_

开头的文件夹
<?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);
}
}
?>

4 个答案:

答案 0 :(得分:3)

无需使用正则表达式,请使用$file[0] == '_'substr($file, 0, 1) == '_'

如果您 想要正则表达式,则需要使用preg_match()来检查:preg_match('/^_/', $file)

答案 1 :(得分:3)

您可以使用substr[docs]之类的:

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

答案 2 :(得分:0)

或者,如果你想使用regexp,你应该使用正则表达式函数,比如preg_match:preg_match('/^_/', $file);但正如ThiefMaster所说,在这种情况下,$file[0] == '_'就足够了。

答案 3 :(得分: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";
}