1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
<?php
class p_grep extends prog {
public static function flag($flags,$flag) {
return (strpos($flags,$flag)!==false);
}
public static function recurse_grep($pattern, $subject, $flags = '') {
// Do a breadth-first search
$dirs = array();
if ( is_dir($subject) ) {
$dirs[] = $subject;
} else {
self::grep($pattern, $subject, $flags);
}
foreach($dirs as $dir) {
$dh = opendir($dir);
while(false !== ( $file = readdir($dh)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
self::recurse_grep($pattern, $subject.'/'.$file, $flags);
}
}
closedir($dh);
}
}
public static function grep($pattern, $file, $flags) {
$lines = preg_split("/\r\n/",file_get_contents($file));
foreach ($lines as $line_number => $line_contents) {
if (preg_match($pattern,$line_contents)>0) {
if (
(self::flag($flags,'r') && !self::flag($flags,'h')) // recursive
|| (self::flag($flags,'H')) // or explicit
) { echo htmlentities($file).': '; }
if (self::flag($flags,'n')) { echo $line_number.': '; }
echo htmlentities($line_contents)."\n";
}
}
}
public static function main($args, $env) {
$me = array_shift($args);
$flags = '';
while (substr($args[0],0,1) == '-') {
$flags .= array_shift($args);
}
$flags = preg_replace('/[ -]/','',$flags);
$pattern = array_shift($args);
foreach ($args as $file) {
if (self::flag($flags,'r')) { self::recurse_grep($pattern, $file, $flags); }
else { self::grep($pattern, $file, $flags); }
}
}
}
|