Jump to content

Reading the right line from a file using fopen?


wwfc_barmy_army

Recommended Posts

Hello, I have this code:

 

$file = fopen("myfile","r");
while(! feof($file))
  {
  if( preg_match( "/^Number\b/", fgets($file) ))
    {
  echo fgets($file);
  	}
  }
fclose($file);

 

I want it to print the line that starts with 'Number' but for some reason it is printing the line AFTER the line that starts with 'Number'  :shrug:

 

Anyone got any suggestions?

 

Thanks.

Of course, the call to fgets used when calling preg_match reads the line that you are really interested in. Then when you call fgets again, it continues from where it left off and reads the following line.

 

You probably want something like:

 

while( ! feof($file))
{
    $line = fgets($file);
    if (preg_match("/^Number\b/", $line))
    {
        echo $line;
    }
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.