Jump to content

Finding the line of a keyword in a text file.


Saurdo

Recommended Posts

Hello! I am building a description system that will be implemented into a gallery script. The script will get the name of the image, find that name in a text file, and read all the text on the same line of the name of the image.

 

I already have a script that reads lines from text files but now I need some help with the finding the line part. I need it to find the keyword and tell me the line it's on. I know strpos() can find the keyword for me but that tells me the amount of characters between the beginning of the file and the position of the keyword. So if anyone has any suggestions or example scripts that'd be awesome.

 

Thanks for the help :D

You can always just implement your own line counting method as well. Just count the number of end of line characters (like \n) and that will give an indication of the line number. I dunno what php functions do this since I've never had to do any string manipulation outside of using xml files.

 

A simple home-made function could be like this:

 

function getPozzy()

{

    $count = 1;

    while (not at the end of the text file)

    {

          $temp = the next line of text;

          if ($temp contains the image name /* use strstr() i think? */) return $count;

          else $count += 1;

    }

    return -1; //Since image name not found.

}

 

That way you can get the text for that line and its position at the same time. Since you already have a script which reads lines from a text file it should be easy for you to read each line into a temporary variable and check it for the image name. Just muck around with the function and have at 'em.

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.