How can PHP be used to search for a specific string in a TXT file and display the content of the matching line?
To search for a specific string in a TXT file and display the content of the matching line using PHP, you can read the file line by line and check each line for the desired string. If a match is found, you can display or store that line. You can achieve this by using functions like fopen(), fgets(), and strpos() in PHP.
<?php
$filename = 'example.txt';
$searchString = 'specific string';
$handle = fopen($filename, "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if (strpos($line, $searchString) !== false) {
echo $line;
break; // If you only want to display the first matching line
}
}
fclose($handle);
} else {
echo "Error opening the file.";
}
?>
Keywords
Related Questions
- How can PHP scripts be adapted to function properly on websites with HTTPS protocols?
- In what scenarios would it be necessary to use exit() or die() functions in PHP code, despite the potential pitfalls?
- What is the significance of using character classes in preg_match for special characters in PHP?