Searching file contents with Iterators

June 4, 2008 – 11:12 am
  1. // the following code returns all lines of source.txt that contain the string Aerosmith.
  2. // Feel free to extend it for your own uses
  3. class FileGrep extends FilterIterator
  4. {
  5.     private $needle;
  6.  
  7.     public function __construct($file, $needle) {
  8.         parent::__construct(new SplFileObject($file));
  9.         $this->needle = $needle;
  10.     }
  11.  
  12.     public function accept()
  13.     {
  14.         if (strpos($this->current(),$this->needle) !== false) {
  15.             return true;
  16.         }
  17.     }
  18.  
  19. }
  20.  
  21. foreach(new FileGrep('source.txt','Aerosmith') as $line) {
  22.     print $line;
  23. }

Post a Comment