Home >Backend Development >PHP Tutorial >How Can I Replace a Specific Line in a Text File Based on a Word?
Replacing a Specific Line in a Text File Based on a Word
In text file manipulation, situations arise where the need to replace a particular line of text based on the presence of a specific word becomes crucial. This necessity can be addressed using various approaches, each suitable for different scenarios.
Small File Handling
For smaller text files that can comfortably fit into memory, a convenient method involves reading the entire file into an array of lines. This array can then be processed using a customized function, efficiently replacing the line containing the specified word.
Here's an example implementation in PHP:
$data = file('myfile'); // reads an array of lines function replace_a_line($data) { if (stristr($data, 'certain word')) { return "replacement line!\n"; } return $data; } $data = array_map('replace_a_line', $data); file_put_contents('myfile', $data);
Large File Handling
For larger text files that exceed available memory limits, a more efficient approach is required. This method involves reading the file line by line, checking for the presence of the desired word, and replacing it in an alternate file. If the replacement is made, the original file is overwritten with the modified contents.
Consider the following PHP implementation:
$reading = fopen('myfile', 'r'); $writing = fopen('myfile.tmp', 'w'); $replaced = false; while (!feof($reading)) { $line = fgets($reading); if (stristr($line,'certain word')) { $line = "replacement line!\n"; $replaced = true; } fputs($writing, $line); } fclose($reading); fclose($writing); // might as well not overwrite the file if we didn't replace anything if ($replaced) { rename('myfile.tmp', 'myfile'); } else { unlink('myfile.tmp'); }
Depending on the file size and resource constraints, these approaches provide effective solutions for replacing specific lines in a text file based on word presence.
The above is the detailed content of How Can I Replace a Specific Line in a Text File Based on a Word?. For more information, please follow other related articles on the PHP Chinese website!