Reputation:
I am trying to search in a txt file using php. It is supposed to search the txt file and display results that it got from the file.
Here is my php
code:
<?php
$file = 'my file.txt';
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";
if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:\n";
echo implode("\n", $matches[0]);
}
else {
echo "No matches found";
}
Upvotes: 0
Views: 212
Reputation: 350137
You should use $file to read the file's contents into the $contents variable. You can use get_file_contents for that. Also, it might be useful to turn this into a function, so you can re-use it for other files and search strings:
function searchInFile($file, $searchFor) {
$contents = get_file_contents($file);
if ($contents === false) return array(); // no file, no match
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";
preg_match_all($pattern, $contents, $matches));
return $matches[0];
}
$matches = searchInFile('my file.txt', 'concert');
if (count($matches)) {
echo "Found matches:\n" . implode("\n", $matches);
} else {
echo "No matches found";
}
Upvotes: 1