dtml3340
2012-05-08 06:26
浏览 282
已采纳

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

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);
}
}
?>

图片转代码服务由CSDN问答提供 功能建议

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

 &lt;?php 
 
 $ dir = __dir __; 
 
 //开启已知目录的文件夹 ,并继续阅读其内容
if(is_dir($ dir)){
 if($ dh = opendir($ dir)){
 echo(“&lt; ul&gt;”); 
 while(($ file  = readdir($ dh))!== false){
 if($ file =='。'|| $ file =='..'|| $ file =='^ [_] * $')继续 ; 
 if(is_dir($ file)){
 echo“&lt; li&gt;&lt; a href ='$ file'&gt; $ file&lt; / a&gt;&lt; / li&gt;”; 
} 
}  
 closedir($ dh); 
} 
} 
?&gt; 
   
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • douhui3330 2012-05-08 06:29
    已采纳

    you can use substr[docs] like :

    ||  substr($file, 0, 1) === '_'
    
    点赞 打赏 评论
  • dongxin8709 2012-05-08 06:28

    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)

    点赞 打赏 评论
  • douyi4912 2012-05-08 06:32

    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.

    点赞 打赏 评论
  • doudi4137 2012-05-08 07:09

    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>
    ";
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题