Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Search files in php, recursive, regex
/*
* 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
You can’t perform that action at this time.