84669 person learning
152542 person learning
20005 person learning
5487 person learning
7821 person learning
359900 person learning
3350 person learning
180660 person learning
48569 person learning
18603 person learning
40936 person learning
1549 person learning
1183 person learning
32909 person learning
How to replace specific lines of text in a file using php?
I don't know the line number. I want to replace lines containing specific words.
You must overwrite the entire file.
So, for a relatively small file, read the file into an array , search for the word, replace the found lines, all the rest is written to the file .
For large files, the algorithm is slightly different, but generally the same.
The important part isFile locking
This is why we prefer databases.
A method that can be used for smaller files that fit in your memory twice:
$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);
Quick note, PHP > 5.3.0 supports lambda functions, so you can remove the named function declaration and shorten the mapping to:
$data = array_map(function($data) { return stristr($data,'certain word') ? "replacement line\n" : $data; }, $data);
Theoretically you could make this a single (harder to follow) php statement:
file_put_contents('myfile', implode('', array_map(function($data) { return stristr($data,'certain word') ? "replacement line\n" : $data; }, file('myfile')) ));
For larger files another (less memory intensive) method should be used:
$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'); }
You must overwrite the entire file.
So, for a relatively small file, read the file into an array , search for the word, replace the found lines, all the rest is written to the file .
For large files, the algorithm is slightly different, but generally the same.
The important part isFile locking
This is why we prefer databases.
A method that can be used for smaller files that fit in your memory twice:
Quick note, PHP > 5.3.0 supports lambda functions, so you can remove the named function declaration and shorten the mapping to:
Theoretically you could make this a single (harder to follow) php statement:
For larger files another (less memory intensive) method should be used: