Searching file contents with Iterators
June 4, 2008 – 11:12 am-
// the following code returns all lines of source.txt that contain the string Aerosmith.
-
// Feel free to extend it for your own uses
-
class FileGrep extends FilterIterator
-
{
-
private $needle;
-
-
public function __construct($file, $needle) {
-
parent::__construct(new SplFileObject($file));
-
$this->needle = $needle;
-
}
-
-
public function accept()
-
{
-
if (strpos($this->current(),$this->needle) !== false) {
-
return true;
-
}
-
}
-
-
}
-
-
foreach(new FileGrep('source.txt','Aerosmith') as $line) {
-
print $line;
-
}
