Re: Searching for a specific line within a file



Gene Kelley wrote:
Hello PHPers,

I'm trying to get at a single line within a text file. For instance, I want to print the line within a the file named "file.txt" that starts with "17:".

file.txt contains (condensed of course):
...
15: This is line 15
16: This is line 16
17: This is line 17 // <- This is the line I want to get
18: This is line 18
19: This is line 19
...

I'm able to get the FIRST line with:

<?php
$file = fopen(,"r");
echo fgets($file);
fclose($file);
?>

I *think* you can do this:

$handle = @fopen("file.txt", "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle);
// run your regex on $buffer which is a single line
// and "break" loop if true

}
fclose($handle);
}

I *think* that will only read in the file a line at a time until your condition is met..

Now, I'm only a couple weeks into PHP and haven't done this, so I may be wrong. If I were writing perl, this is what I would do if I had a very large file. This isn't perl though, so YMMV.

Neither Jerry or Geoff had raised that possibility (I'm unsure why), so I though I should.

If the file is small, a few 100K or so, I'd just slurp it all up with "file" as has been suggested.

Jeff


Output:
1: This is line 1

Is there one function that might be out there to do this? and if so, what would be the most efficient way? Obviously, I'd like to avoid reading in the entire contents of the file (could get quite large) then say, explode()ing into an array, then searching the array for the contents of the line to print.

Am I even on the right track here? Oh, well... It's Friday!!! :-)

Thanx

Gene
.



Relevant Pages