简体   繁体   中英

Recursive directory searcer PHP

我如何编写一个带有geven字符串并返回整个路径以及php中文件名的递归目录搜索器?

The php function dir will help you.

http://php.net/manual/en/class.dir.php

There is an example in the notes of the docs (by sojka at online-forum dot net) that shows doing this, which I have included below...

<?php
public static function getTreeFolders($sRootPath = UPLOAD_PATH_PROJECT, $iDepth = 0) {
      $iDepth++;
      $aDirs = array();
      $oDir = dir($sRootPath);
      while(($sDir = $oDir->read()) !== false) {
        if($sDir != '.' && $sDir != '..' && is_dir($sRootPath.$sDir)) {
          $aDirs[$iDepth]['sName'][] = $sDir;
          $aDirs[$iDepth]['aSub'][]  = self::getTreeFolders($sRootPath.$sDir.'/',$iDepth);
        }
      }
      $oDir->close();
      return empty($aDirs) ? false : $aDirs;
}
?>

There are lots of other similar examples from other people on the same page, so find one that you like and go from there...

You could iterate trough the dirctory using a RecursiveDirectoryIterator. Look at this:

$search_query = "test";
$directory = new RecursiveDirectoryIterator('/path/');
$iterator = new RecursiveIteratorIterator($directory);
$result = new RegexIterator($iterator, '/^.+\'.$search_query.'$/i', RecursiveRegexIterator::GET_MATCH);

Then (array) $result should usually contain all filenames in which 'test' was found under '/path/'.

Hope it helps ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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