如何使用php替换文本文件中的特定行? [英] how to replace a particular line in a text file using php?

查看:55
本文介绍了如何使用php替换文本文件中的特定行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用php替换特定行.我不知道行号.我要替换包含特定单词的行.

how to replace a particular row using php. I dont know the line number. I want to replace a line containing a particular word.

推荐答案

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

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

这篇关于如何使用php替换文本文件中的特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆