Replacing Lines in Text Files Based on Word Matching Using PHP
In scenarios where the line number is unknown, replacing specific lines based on word matching can be a challenging task. Fortunately, PHP offers several effective approaches to tackle this situation:
For Smaller Files (Fit into Memory):
- Read the entire file into an array of lines using file('myfile').
-
Create a function to replace the desired line, such as replace_a_line($data):
- Check if the line contains the target word using stristr($data, 'certain word').
- If found, return the replacement line as a string.
- Otherwise, return the original line.
- Apply the replacement function to each line in the array using array_map('replace_a_line', $data).
- Write the modified array back to the file using file_put_contents('myfile', $data).
-
Enhance the method by using lambda functions to simplify the array_map:
- $data = array_map(function($data) { ... }, $data);
For Larger Files (Memory Intensive):
- Open the file for reading and writing using fopen('myfile', 'r') and fopen('myfile.tmp', 'w') respectively.
- Set a flag to indicate if a replacement is made ($replaced).
- Read each line in the input file using fgets($reading).
- Check for the presence of the target word using stristr($line, 'certain word').
- If found, replace the line with the modified version.
- Write the updated line to the output file using fputs($writing, $line).
- Close the file handles after processing.
- Replace the original file with the modified one only if a replacement was made (rename('myfile.tmp', 'myfile')) or delete the temporary file if no replacement was needed (unlink('myfile.tmp')).
The above is the detailed content of How to Replace Lines in Text Files Based on Word Matching in PHP?. For more information, please follow other related articles on the PHP Chinese website!