Skip to content

Instantly share code, notes, and snippets.

@UziTech
Last active June 17, 2016 15:45
Show Gist options
  • Save UziTech/af404d1be02131c91cc592e1dc27a59b to your computer and use it in GitHub Desktop.
Save UziTech/af404d1be02131c91cc592e1dc27a59b to your computer and use it in GitHub Desktop.
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