Re: Need a simple one time search utility

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Sat, Apr 12, 2008 at 4:31 PM, Al <news@xxxxxxxxxxxxx> wrote:

> I know how to script one to do the job; but, I was hoping to save a few
> hours..


here; ill spare you the few hours ;)  as it stands this is designed to be
invoked from the cli, but theres a class in here that does all the heavy
lifting.  im sure you can easily adapt it to suit your needs, but likely you
can use it out-of-the-box.  there are some limitations,
recursive only searches
path / filename of matches not returned
cant pipe to it as in
command | php grep.php args

<?php
if($argv[1] == '--help') {
        die(usage());
}

$flags = Grep::PREG_GREP_STD;
$pattern = $argv[1];
$path = $argv[2];
if(isset($argv[3])) {
        $flags = $argv[3];
}

echo Grep::simpleFactory($pattern, $path, $flags);

function usage() {
        echo
<<<USAGE
php grep.php <pattern> <path> [flags]
simple php implementation of grep
note: this version is recursive only
a flag = 1 will invert the search so that results that do not match will be
returned

USAGE;
}

class Grep {
        const PREG_GREP_STD = 0;
        const PREG_GREP_INVERT = 1;     // <- ganked from quercus ;)

        private $matches = array();
        private $pattern = null;
        private $path = '';
        private $flags = '';

        public function __construct($pattern, $path, $flags=0) {
                $this->pattern = $pattern;
                $this->path = $path;
                $this->flags = $flags;
                $this->search();
        }

        public static function simpleFactory($pattern, $path, $flags=0) {
                return new self($pattern, $path, $flags);
        }

        public function setPattern($pattern) {
                $this->pattern = $pattern;
        }

        public function setPath($path) {
                if(is_dir($path) || is_file($path)) {
                        $this->path = $path;
                }
        }

        public function setFlags($flags) {
                $this->flags = $flags;
        }

        public function search() {
                $rdi = new RecursiveDirectoryIterator($this->path);
                foreach(new RecursiveIteratorIterator($rdi,
RecursiveIteratorIterator::SELF_FIRST) as $curFile) {
                        $this->matches = array_merge($this->matches,
preg_grep("/{$this->pattern}/", file($curFile)));
                }
        }

        public function __toString() {
                return implode($this->matches);
        }
}
?>

enjoy,

-nathan

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux