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 $matches
if (preg_match_all($pattern, $contents, $matches))
{
echo "Found matches:\n";
echo implode("\n", $matches[0]);
}
else
{
echo "No matches found";
}
PHP to search a word within txt file and echo the whole line
This answer doesn't take into account fields in your source data, since at the moment you're just bulk-matching the raw text and interested in getting full lines. There is a much simpler way to accomplish this, ie. by using file
that loads each line into an array member, and the application of preg_grep
that filters an array with a regular expression. Implemented as follows:
$lines = file('ids.txt', FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES); // lines as array
$search = preg_quote($_POST['search'], '~');
$matches = preg_grep('~\b' . $search . '\b~', $lines);
foreach($matches as $line => $match) {
echo "Line {$line}: {$match}\n";
}
In related notes, to match only complete words, instead of substrings, you need to have word boundaries \b
on both sides of the pattern. The loop above outputs both the match and the line number (0-indexed), since array index keys are saved when using preg_grep
.
PHP Search for a keyword from a text file, prints the whole line with the keyword, then counts how many lines were printed
Here is essentially a one liner that may work:
$array = array_filter(array_map(function($v){
return (stripos($v,'ERR:') !== false)? $v : false;
},array_filter(file('Sample.log',FILE_SKIP_EMPTY_LINES),function($v){
return (!empty(trim($v)));
})));
# This will implode the lines
echo (!empty($array))? implode('<br />',$array) : '';
# This will count the array
echo ((!empty($array))? count($array) : 0).' matches found.';
First it uses file()
to turn a file into an array using new lines, then filters empty lines that may exist, then uses array_map()
to iterate, then inside that uses stripos()
to search each line for ERR:
, then returns the ones that match (or false
if no match), then array_filter()
with no callback to remove all the values with false
(empty). The last two lines implode the remaining array and then writes how many values are in the final array using count()
.
Find string in a text file with PHP
I think the problem is with the regex pattern. But since there is some other things that can be done better I add that too.
$list = file_get_contents("peoplelist.txt");
list($something, $name, $somethingelse, $boss) = explode(',',$line);
$name = str_replace(' ', '.', strtolower($name));
echo $name;
$file = 'people.txt';
$contents = file_get_contents($file);
$pattern = "/" . $name . "/m";
if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:\n";
echo implode("\n", $matches[0]);
}
else{
echo "No matches found";
}
Your regex didnt make sense. You wanted it to start with anything.
Then why force start with? And off course the literal $.
Searching multiple strings in one txt file
<?php
$search1 = "value 1";
$search2 = "value 2";
$lines = file('my_file.txt');
foreach($lines as $line)
{
if(stristr($line,$search1) || stristr($line,$search2))
echo " $line <br>";
}
?>
Please see if this code works.
This will give you the lines where $search1
or $search2
appear.
Thank you :)
PHP search text file line by line for two strings then output line
Assuming the values you're searching for are separated by a space, and they will both always be present, explode
should do the trick:
$search = explode(' ', $_REQUEST["search"]); // change ' ' to ',' if you separate the search terms with a comma, etc.
// Read from file
$lines = file('archive.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[0]) !== false && strpos($line, $search[1] !== false)) {
echo"<html><title>SEARCH RESULTS FOR: $search</title><font face='Arial'> $line <hr>";
}
}
I'll leave it up to you to add some validation to make sure there are always two elements in the $search
array, etc.
Related Topics
How to PHP-Unserialize a Jquery-Serialized Form
Why Are My Cookies Not Setting
Create Programmatically a Woocommerce Product Variation With New Attribute Values
PHP Output Showing Little Black Diamonds With a Question Mark
Setting the PHP Default Encoding to Utf-8
Difference Between MySQL, MySQLi and Pdo
Fpdf Error: Some Data Has Already Been Output, Can't Send Pdf
What Is the Canonical Way to Determine Commandline Vs. Http Execution of a PHP Script
How to Upload Large Files Above 500Mb in PHP
How to List All Months Between Two Dates
Finding the Subsets of an Array in PHP
Listing All the Folders Subfolders and Files in a Directory Using PHP
How to Get the User'S Local Time Instead of the Server'S Time
Is PHP Compiled or Interpreted