How can PHP be used to search for specific words within a text file and manipulate surrounding lines?
To search for specific words within a text file and manipulate surrounding lines using PHP, you can read the file line by line, search for the specific word using a regular expression or strpos function, and then manipulate the surrounding lines as needed. You can store the lines in an array, make the necessary changes, and then write the modified lines back to the file.
<?php
// Open the text file for reading
$file = fopen("example.txt", "r");
// Array to store lines
$lines = [];
// Search term
$searchTerm = "specific_word";
// Read the file line by line
while (!feof($file)) {
$line = fgets($file);
// Check if the line contains the search term
if (strpos($line, $searchTerm) !== false) {
// Manipulate surrounding lines
// For example, you can add a prefix to the previous line
if (!empty($lines)) {
$lines[count($lines) - 1] = "Prefix: " . $lines[count($lines) - 1];
}
}
// Store the line in the array
$lines[] = $line;
}
// Close the file
fclose($file);
// Open the text file for writing
$file = fopen("example.txt", "w");
// Write the modified lines back to the file
foreach ($lines as $line) {
fwrite($file, $line);
}
// Close the file
fclose($file);
?>
Related Questions
- How can PHP be used to securely pass variables in the URL without compromising sensitive information like passwords?
- How can PHP developers ensure that only specific characters are allowed in a user input string?
- How can AJAX and JavaScript be integrated with PHP to enhance the functionality of displaying database queries in URLs?