Replace an entire line in a text file when a specific word is encountered
P粉883278265
P粉883278265 2023-10-18 16:59:05
0
2
453

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.

P粉883278265
P粉883278265

reply all(2)
P粉138711794

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.

P粉155710425

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');
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!