You have got a couple options, but none are "simple":
a) exec()
and use the system grep
command, which can report line numbers:
exec("grep -n 'your pattern here' file.txt", $output);`
b) Slurp in the file using file_get_contents()
, split it into an array of lines, then use preg_grep()
to find the matching lines.
$dat = file_get_contents('file.txt');
$lines = explode($dat, "\n");
$matches = preg_grep('/your pattern here/', $lines);
c) Read the file in line-sized chunks, keep a running line count, and do your pattern match on each line.
$fh = fopen('file.txt', 'rb');
$line = 1;
while ($line = fgets($fh)) {
if (preg_match('/your pattern here/', $line)) {
... whatever you need to do with matching lines ...
}
$line++;
}
Each has its ups and downs
a) You're invoking an external program, and if your pattern contains any user-supplied data, you're potentially opening yourself up to the shell equivalent of an SQL injection attack. On the plus side, you don't have to slurp in the entire file and will save a bit on memory overhead.
b) You're safe from shell injection attacks, but you have to slurp in the entire file. If your file is large, you'll probably exhaust available memory.
c) You're invoking a regex every line, which would have significant overhead if you're dealing with a large number of lines.
preg_match_all
for this. – Adams