0

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.
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
Brit24
  • 65
  • 8
  • You could use a regex. Maybe something like https://regex101.com/r/xwzlgZ/2/... or you could use `strpos` and `substr` but you won't know if it is a partial match with that. – chris85 Apr 20 '17 at 22:12

3 Answers3

1

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

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);
}
jh1711
  • 2,288
  • 1
  • 12
  • 20
0

Work for me

$file = file_get_contents("file.txt");
$lines = explode("\n", $file);
$line_contains = array();
foreach ($lines as $line) {
    if (strpos($line, 'Text Want Search') !== FALSE) {
         $line_contains[] = $line;
    }
}
$line_contains_print = implode("\n", $line_contains);
print $line_contains_print;

Actually I use above code to remove line that contains a text. Like this,

$file = file_get_contents("file.txt");
$lines = explode("\n", $file);
$exclude = array();
foreach ($lines as $line) {
    if (strpos($line, 'want to remove') !== FALSE) {
         continue;
    }
    $exclude[] = $line;
}
$rm_match_line = implode("\n", $exclude);
print $rm_match_line;
Toing
  • 1
  • 1