How can PHP be used to search for specific text within a file and output the matching lines?
To search for specific text within a file and output the matching lines using PHP, you can read the file line by line and use the `strpos()` function to check if the desired text is present in each line. If a match is found, you can then output that line.
<?php
$filename = 'example.txt';
$searchText = 'specific text';
$handle = fopen($filename, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if (strpos($line, $searchText) !== false) {
echo $line;
}
}
fclose($handle);
} else {
echo "Error opening the file.";
}
?>
Related Questions
- What is the correct way to use echo within PHP to display the desired output?
- How can JavaScript be used to enhance the deletion process in PHP applications, particularly when interacting with backend scripts asynchronously?
- What are some common methods for tracking visitor numbers on a website, specifically focusing on PHP implementation?