PHP to search within txt file and echo the whole line
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 $matchesif(preg_match_all($pattern, $contents, $matches)){ echo "Found matches:\n"; echo implode("\n", $matches[0]);}else{ echo "No matches found";}
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.
<?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 messageif(!$found){ echo 'No match found';}
Here I'm using the $found
variable to find out if a match was found.