【问题标题】:Recursively search sub directories, ignore directories PHP递归搜索子目录,忽略目录 PHP
【发布时间】:2016-10-31 01:05:31
【问题描述】:

我正在使用 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);
      }
    }
?>

【问题讨论】:

    标签: javascript php ajax search


    【解决方案1】:

    更新的代码格式:

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

    试试这个

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

    【讨论】:

    • 这就是为什么这个有效的脚本被否决了。从 android 应用发布可以更改代码格式。现在我已经修好了
    猜你喜欢
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 2011-08-15
    相关资源
    最近更新 更多