Last active
June 17, 2016 15:45
-
-
Save UziTech/af404d1be02131c91cc592e1dc27a59b to your computer and use it in GitHub Desktop.
Search files in php, recursive, regex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* License: MIT | |
*/ | |
/** | |
* Search files in a directory by string or regex | |
* @param string $root Directory to search | |
* @param string $q Search term | |
* @param bool $recursive [optional] Search lower directories. Default = TRUE | |
* @param bool $isRegex [optional] Search term is a regular expression. Default = FASLE | |
* @return SplFileInfo[] An array of files https://secure.php.net/manual/en/class.splfileinfo.php | |
*/ | |
function searchDirectory($root, $q, $recursive = true, $isRegex = false) { | |
if ($isRegex) { | |
$regex = $q; | |
} else { | |
$regex = "|".preg_quote($q)."[^/\\\\]*$|i"; | |
} | |
if ($recursive) { | |
$directory = new RecursiveDirectoryIterator($root); | |
$iterator = new RecursiveIteratorIterator($directory); | |
} else { | |
$iterator = new DirectoryIterator($root); | |
} | |
$files = new RegexIterator($iterator, $regex, RecursiveRegexIterator::MATCH); | |
return iterator_to_array($files, false); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment