I have this code which is search a specific word from a single file. But i want to search the word from the multiple files in a directory and its sub-directories.
After Search it should show the line number and the word found with limited characters from a line after found word. And a specific title from the database according to the file name so we can link the found word from the each file to the specified link to see the found word in that file.
<?php
$filename = "001.doc";
$searchWord = "PHP";
try {
$fileHandle = fopen($filename, 'r');
if ($fileHandle === false) {
throw new Exception("Error opening the file.");
}
$lineNumber = 1;
$found = false;
echo "Specific word: " . $searchWord.'<br>';
while (($line = fgets($fileHandle)) !== false) {
if (stripos($line, $searchWord) !== false) {
echo "Word found on line " . $lineNumber . ": " . $line.'<br>';
$found = true;
}
$lineNumber++;
}
if (!$found) {
echo "Word not found in the file.";
}
fclose($fileHandle);
} catch (Exception $e) {
echo "An error occurred: " . $e->getMessage();
}
?>
source https://stackoverflow.com/questions/76940533/php-word-search-in-text-file-locate-and-display-line-numbers
No comments:
Post a Comment