PHP to search within txt file and echo the whole line

PhpSearchEchoText Files

Php Problem Overview


Using php, I'm trying to create a script which will search within a text file and grab that entire line and echo it.

I have a text file (.txt) titled "numorder.txt" and within that text file, there are several lines of data, with new lines coming in every 5 minutes (using cron job). The data looks similar to:

2 aullah1
7 name
12 username

How would I go about creating a php script which will search for the data "aullah1" and then grab the entire line and echo it? (Once echoed, it should display "2 aullah1" (without quotations).

If I didn't explain anything clearly and/or you'd like me to explain in more detail, please comment.

Php Solutions


Solution 1 - Php

And a PHP example, multiple matching lines will be displayed:

<?php
$file = 'somefile.txt';
$searchfor = 'name';

// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');

// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
   echo "Found matches:\n";
   echo implode("\n", $matches[0]);
}
else{
   echo "No matches found";
}

Solution 2 - Php

Do it like this. This approach lets you search a file of any size (big size won't crash the script) and will return ALL lines that match the string you want.

<?php
$searchthis = "mystring";
$matches = array();

$handle = @fopen("path/to/inputfile.txt", "r");
if ($handle)
{
    while (!feof($handle))
	{
        $buffer = fgets($handle);
		if(strpos($buffer, $searchthis) !== FALSE)
			$matches[] = $buffer;
    }
    fclose($handle);
}

//show results:
print_r($matches);
?>

Note the way strpos is used with !== operator.

Solution 3 - Php

Using file() and strpos():

<?php
// What to look for
$search = 'foo';
// Read from file
$lines = file('file.txt');
foreach($lines as $line)
{
  // Check if the line contains the string we're looking for, and print if it does
  if(strpos($line, $search) !== false)
    echo $line;
}

When tested on this file:

> foozah
> barzah
> abczah

It outputs:

> foozah


Update:
To show text if the text is not found, use something like this:

<?php
$search = 'foo';
$lines = file('file.txt');
// Store true when the text is found
$found = false;
foreach($lines as $line)
{
  if(strpos($line, $search) !== false)
  {
    $found = true;
    echo $line;
  }
}
// If the text was not found, show a message
if(!$found)
{
  echo 'No match found';
}

Here I'm using the $found variable to find out if a match was found.

Solution 4 - Php

$searchfor = $_GET['keyword'];
$file = 'users.txt';

$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";

if (preg_match_all($pattern, $contents, $matches)) {
    echo "Found matches:<br />";
    echo implode("<br />", $matches[0]);
} else {
    echo "No matches found";
    fclose ($file); 
}

Solution 5 - Php

looks like you're better off systeming out to system("grep \"$QUERY\"") since that script won't be particularly high performance either way. Otherwise http://php.net/manual/en/function.file.php shows you how to loop over lines and you can use http://php.net/manual/en/function.strstr.php for finding matches.

Solution 6 - Php

one way...

$needle = "blah";
$content = file_get_contents('file.txt');
preg_match('~^(.*'.$needle.'.*)$~',$content,$line);
echo $line[1];

though it would probably be better to read it line by line with fopen() and fread() and use strpos()

Solution 7 - Php

Slightly modified approach of the Upvoted answer to support multiple directories and variable keywords through a GET variable (if you wish to do it that way)

if (isset($_GET["keyword"])){

   foreach(glob('*.php') as $file) { 

      $searchfor = $_GET["keyword"];
      
      // the following line prevents the browser from parsing this as HTML.
      header('Content-Type: text/plain');
      
      // get the file contents, assuming the file to be readable (and exist)
      $contents = file_get_contents($file);
      // escape special characters in the query
      $pattern = preg_quote($searchfor, '/');
      // finalise the regular expression, matching the whole line
      $pattern = "/^.*$pattern.*\$/m";
      // search, and store all matching occurences in $matches
      if(preg_match_all($pattern, $contents, $matches)){
         echo "Found matches:\n";
         echo $file. "\n";
         echo implode("\n", $matches[0]);
         echo "\n\n";
      }
      else{
      //  echo "No matches found";
      }
   }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaullahView Question on Stackoverflow
Solution 1 - PhpLekensteynView Answer on Stackoverflow
Solution 2 - PhpshamittomarView Answer on Stackoverflow
Solution 3 - PhpFrxstremView Answer on Stackoverflow
Solution 4 - Phpuser5521731View Answer on Stackoverflow
Solution 5 - PhpNovikovView Answer on Stackoverflow
Solution 6 - PhpCrayon ViolentView Answer on Stackoverflow
Solution 7 - PhpPearceView Answer on Stackoverflow