Replacing Specific Lines in a Text File with PHP
Within a text file, selectively replacing lines based on the presence of a particular word is a common requirement. In this regard, PHP provides several approaches to accomplish this task.
Using Array Functions for Smaller Files (Fit into Memory)
For text files that fit into memory, the following approach can be employed:
$data = file('myfile'); // Array of lines function replace_a_line($data) { return (stristr($data, 'certain word')) ? "replacement line!\n" : $data; } $data = array_map('replace_a_line', $data); file_put_contents('myfile', $data);
Lambda functions in PHP versions > 5.3.0 allow for a concise version:
$data = array_map(function($data) { return (stristr($data, 'certain word')) ? "replacement line\n" : $data; }, $data);
For Larger Files (Memory-Intensive)
With larger files, the below approach iterates line-by-line without loading the entire file into memory:
$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); if ($replaced) rename('myfile.tmp', 'myfile'); else unlink('myfile.tmp');
By implementing these techniques, you can effectively replace specific lines in a text file based on a word match.
The above is the detailed content of How Can I Replace Specific Lines in a Text File with PHP?. For more information, please follow other related articles on the PHP Chinese website!