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("file.txt","r");
echo fgets($file);
fclose($file);
?>

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

Gene,

Either way, you need to read the file and search it. There isn't any PHP function to do that automatically, which leaves you the choice of reading the whole file in at once, or read it one line at a time, looking for the one you want.

Alternatively, if you can execute system utilities from PHP (many shared hosts disallow this), you could use grep to get the line(s).

==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex@xxxxxxxxxxxxx
==================
.



Relevant Pages

  • Re: Advice about fetching user information
    ... but actually *selecting* them in MySQL ... PHP scripts and use a gaugefunction to time pretty much every ... The same is pretty much true for searching an array in PHP - ... But I wouldn't be searching. ...
    (comp.lang.php)
  • Re: Date code
    ... > I'm searching but not finding:( ... I don't have a worked out example in PHP for Zoeller's algorithm for ... You can then build your own array for the month. ...
    (comp.lang.php)
  • Searching for a specific line within a file
    ... echo fgets; ... Obviously, I'd like to avoid reading in the entire contents of the file then say, explodeing into an array, then searching the array for the contents of the line to print. ...
    (comp.lang.php)
  • Re: Need help on PHP for MPE/ix
    ... Here is the syntax of the dbupdate intrinsic in PHP: ... assoc array of item values) ... Please let me know if you have any more suggesstions to solve this problem. ... Pavan Kumar Rati wrote: ...
    (comp.sys.hp.mpe)
  • Re: Using a RegEx as a "variable" WITHIN an array?
    ... believe the PHP one is also based upon. ... combination of 1 or more numerics in this instance would give you your ... add this to your array - you could then do a pattern match on the array ... > Dim selCriteria as String ...
    (microsoft.public.dotnet.framework.aspnet)