I have a program that searches a text file to see if a certain string is in that file, which I have gotten to work fine. What I need to know is how to print a particular line of that text file. For example, if the file lists three street names each on its own line, and the program searches for one of them, I would want it to print out only the line that has that street name on it.
If the file looked like this: and the word being searched for was Rose Road
, I want it to only print out 6784 Rose Road
4543 Drock Drive
1254 HeadHill Road
6784 Rose Road
This is what I have so far, which checks if it's in the file, but I am just unsure how to print out a particular line.
$roadName = "Rose";
$handle = fopen("streets.txt", "r");
if(strpos(file_get_contents("streets.txt"),$roadName) !== false) //Checks to make sure its in the file.
{
echo fgets($handle); //This is what I was trying, but it only prints the 1st line.
}
I would explode the lines into an array and the check every line:
$roadName = "Rose";
$file=file_get_contents("streets.txt")
if(strpos($file,$roadName) !== false) //Checks to make sure its in the file.
{
$lines = explode(PHP_EOL,$file);
foreach($lines as $line) {
if (strpos($line,$roadName) !== false) echo($line);
}
file_get_contents
and strpos
have no effect on the file handle, so fgets
just read from the beginning of the file.
You can read each line with fgets
, test if it matches the string, and then print it.
while ($line = fgets($handler)) {
if (strpos($line, $roadName) !== false) {
echo $line;
break;
}
}
If the file is very large, this is better than the solution that uses file_get_contents
, because it doesn't have to read the entire file into memory and then create a huge array of all the lines.