且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用php替换文本文件中的特定行?

更新时间:2023-01-15 17:44:51

您可以对可放入内存两次的较小文件使用一种方法:

One approach that you can use on smaller files that can fit into your memory twice:

$data = file('myfile'); // reads an array of lines
function replace_a_line($data) {
   if (stristr($data, 'certain word')) {
     return "replaement line!\n";
   }
   return $data;
}
$data = array_map('replace_a_line',$data);
file_put_contents('myfile', implode('', $data));

一个简短的说明,PHP> 5.3.0支持lambda函数,因此您可以删除命名的函数声明并将映射缩短为:

A quick note, PHP > 5.3.0 supports lambda functions so you can remove the named function declaration and shorten the map to:

$data = array_map(function($data) {
  return stristr($data,'certain word') ? "replacement line\n" : $data;
}, $data);

从理论上讲,您可以使它成为单个(很难遵循)的php语句:

You could theoretically 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'))
));

您应该对较大的文件使用另一种(较少占用内存的)方法:

Another (less memory intensive) approach that you should use for larger files:

$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');
}