duanbinren8906 2014-06-04 21:07
浏览 34
已采纳

PHP:如何遍历目录并排除数组中出现的任何内容

I have a code that lists all of the files and folders in a directory. What I can't figure out is how to exclude certain files based on a list of values in an array. For instance, I have an array like the one below. I want to reference this list and exclude any item that contains one of those substrings:

$hideDir = array('.php', '.html', '.css');

Here's my current loop. Any thoughts on what I'm doing wrong?

echo '<ul>';
foreach($hideDir as $v) {
if ($handle = opendir('.')) {
    while (false !== ($entry = readdir($handle))) { 
        if (strpos($entry, $v) > -1) {
            //do nothing
        }else{
            echo '<li>' . "$entry" . '</li>' . "
";
        }
    }
}
closedir($handle);
}
echo '</ul>';
  • 写回答

1条回答 默认 最新

  • douye9822 2014-06-04 21:12
    关注

    You're close, but you should drop the whole foreach. Just check while reading the dir, whether the current entry's extension (that can be checked with pathinfo()) is in the array, using in_array():

    echo '<ul>';
    if ($handle = opendir('.')) {
        while (false !== ($entry = readdir($handle))) {
            // Get entry info
            $entryInfo = pathinfo(__DIR__ . DIRECTORY_SEPARATOR . $entry);
    
            // Is this a "hidden" extension?
            if (in_array($entryInfo['extension'], $hideDir)) {
                // Skip it!
                continue;
            }            
    
            // Otherwise, just list it
            echo '<li>' . "$entry" . '</li>' . "
    ";
        }
    }
    closedir($handle);
    echo '</ul>';
    

    Notice that the extension does not contain the dot in front of it, so it should be:

    $hideDir = array('php', 'html', 'css');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度