Reputation: 32878
How can i write an recursice directory searcher that takes a geven string and return the whole path plus the filename in php?
Upvotes: 1
Views: 313
Reputation: 1128
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 ;)
Upvotes: 0
Reputation: 13972
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...
Upvotes: 3