note 75900 added to function.DirectoryIterator-construct

From: Date: Wed, 20 Jun 2007 23:44:58 +0000
Subject: note 75900 added to function.DirectoryIterator-construct
Groups: php.notes 
Request: Send a blank email to php-notes+get-127842@lists.php.net to get a copy of this message
I needed to match in directory tree file name(s) by regular expression. Code is based on Marcus Börger class DirectoryTreeIterator http://cvs.php.net/viewvc.cgi/php-src/ext/spl/examples/ and on examples given in his lecture Introduction to object oriented PHP at PHP Quebec conference 2007 http://talks.somabo.de/ <?php class KeyFilter extends FilterIterator { private $_rx; function __construct(Iterator $it, $regex) { parent::__construct($it); $this->_rx= $regex; } function accept() { return ereg($this->_rx,$this->getInnerIterator()->key()); } protected function __clone() { return false; } } class DirMach extends KeyFilter { function __construct($path , $regex) { parent::__construct( new DirectoryTreeIterator($path), $regex); } function current() { return parent::key(); } function key() { return parent::key(); } } class DirectoryTreeIterator extends RecursiveIteratorIterator { /** Construct from a path. * @param $path directory to iterate */ function __construct($path) { try { parent::__construct( new RecursiveCachingIterator( new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_FILENAME ), CachingIterator::CALL_TOSTRING|CachingIterator::CATCH_GET_CHILD ), parent::SELF_FIRST ); } catch(Exception $e) { echo $e->getMessage(); exit; } } /** @return the current element prefixed with ASCII graphics */ function current() { if ($this->hasChildren()) $this->next(); return $this->key(); } /** Aggregates the inner iterator */ function __call($func, $params) { return call_user_func_array(array($this->getSubIterator(), $func), $params); } } $PathToSearch = 'path_to_search'; $regex = 'regular_expression'; $FileList = new DirMach($PathToSearch, $regex); foreach ($FileList as $file) { $match[] = $file; } echo '<pre>'; var_dump($match); echo '</pre>'; ?> ---- Server IP: 69.147.83.197 Probable Submitter: 89.216.148.166 ---- Manual Page -- http://www.php.net/manual/en/function.DirectoryIterator-construct.php Edit -- https://master.php.net/note/edit/75900 Del: integrated -- https://master.php.net/note/delete/75900/integrated Del: useless -- https://master.php.net/note/delete/75900/useless Del: bad code -- https://master.php.net/note/delete/75900/bad+code Del: spam -- https://master.php.net/note/delete/75900/spam Del: non-english -- https://master.php.net/note/delete/75900/non-english Del: in docs -- https://master.php.net/note/delete/75900/in+docs Del: other reasons-- https://master.php.net/note/delete/75900 Reject -- https://master.php.net/note/reject/75900 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#127842) next »