Replacing a Specific Line in a Text File Using PHP
Need to edit a text file and zero in on a specific line containing a particular word? Let's dive into the world of PHP and explore two techniques to replace that line with ease.
Method 1: In-Memory Line Replacement
For smaller files that can be comfortably held in memory, you can use the following approach:
$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);
Method 2: Less Memory Intensive Line Replacement
For larger files, try this more memory-conserving method:
$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); // Don't overwrite if nothing replaced if ($replaced) { rename('myfile.tmp', 'myfile'); } else { unlink('myfile.tmp'); }
There you have it! The choice of approach depends on the size of your file and your memory constraints. Remember, for large files, the second method is your ally, while the first method excels with smaller files.
The above is the detailed content of How to Replace a Specific Line in a Text File Using PHP?. For more information, please follow other related articles on the PHP Chinese website!