繁体   English   中英

递归搜索子目录,忽略目录PHP

[英]Recursively search sub directories, ignore directories PHP

我使用AJAX和文本输入将搜索字符串发送到当前的PHP文件,此脚本在目录中搜索文件和文件夹,但没有子文件夹。 我想要的是只在目录和子目录中搜索文件,然后列出它们的东西。 像这样的结构:

Corecube
-Categories
--Movies
---File 1
---File 2
---File 3
--Music
---File 1
---File 2
---File 3
--Pictures
---File 1
---File 2
---File 3
-MainCategories
--Code
---File 1
---File 2
---File 3
--Gifs
---File 1
---File 2
---File 3

然后在“ Corecube”的父级中进行搜索,但仅从每个子目录中吐出文件名,而没有实际目录。 我已经尝试过对当前脚本进行几次迭代,但最终每次都将其破坏。

<?php
    $dir = "../corecube";
    $key = $_GET['key'];

    // Open a known directory, and proceed to read its contents
    if (is_dir($dir)) {
      if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
          if($file == $key){
            echo('<a href="'.$dir . $file.'">'. $file .'</a>'."\n");
          }
        }
      closedir($dh);
      }
    }
?>

更新的代码格式:

您需要在嵌套文件夹中搜索文件

尝试这个

<?php 
function matchFile($filename, $path, $key) 
{  
    if(preg_match("/$key/i",$filename)) 
    {       
        echo('<a href="'.$path.'">'. $filename .'</a>'."<br>"); //use regex than casual '==' for flexible search    
    } 
}

function getListDir($dir, $key) 
{   
    if(strlen($key)<2) die("insert min 2 length string"); //for avoid return/display bunch of list file     
    if(is_dir($dir))    
    {       
        if ($dh = opendir($dir)) 
        {
            while (($file = readdir($dh)) !== false) 
            {
                $newItem="$dir/$file";
                if($file=='.' || $file=="..")
                {
                    continue;
                }
                elseif(is_dir("$newItem"))
                {
                    getListDir("$newItem", $key);
                }
                elseif(is_file("$newItem"))
                {
                    matchFile($file, $newItem, $key);
                }
                else
                {
                    //do nothing
                }
            }           
        }           
        else            
        {
            die ("cant open folder: $folder");          
        }   
    } 
}

//run script 
$initialFolder="initialfolder"; // change this into "../corecube"
$key = (isset($_GET["key"]))?$_GET['key']:NULL; 
getListDir($initialFolder, $key); 
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM