class RegexFilter extends FilterIterator {
protected $regex;
public function __construct(Iterator $it, $regex) {
parent::__construct($it);
$this->regex = $regex;
}
public function accept() {
return preg_match($this->regex, $this->current());
}
}
function find_files($path, $pattern, $include_dir=FALSE) {
$objects = new RecursiveDirectoryIterator($path);
$objects = new RecursiveIteratorIterator($objects, RecursiveIteratorIterator::SELF_FIRST);
$objects = new RegexFilter($objects, $pattern);
return $objects;
}
Example usage:
$files = find_files('/tmp', '/.py$/');
foreach ($files as $file) {
echo $file;
}
Previously using php 4:
function find_files4($path, $pattern, $callback=null) {
$path = rtrim(str_replace("\\", "/", $path), '/') . '/';
$matches = Array();
$entries = Array();
$dir = dir($path);
while (false !== ($entry = $dir->read())) {
$entries[] = $entry;
}
$dir->close();
$files = array();
foreach ($entries as $entry) {
$fullname = $path . $entry;
if ($entry != '.' && $entry != '..' && is_dir($fullname)) {
$this->find_files($fullname, $pattern, $callback);
} else if (is_file($fullname) && preg_match($pattern, $entry)) {
if (!$callback) {
$files[] = $fullname;
} else {
call_user_func($callback, $fullname);
}
}
}
if (!$callback) {
return $files;
}
}
No comments:
Post a Comment