使用php更改文件中的一行

时间:2015-02-23 06:22:44

标签: php

mytext.txt

我有一个名为mytext.txt的文件,它包含一些数据,如下所示:

This is the file contain new data.

That have some error.

that need to fix.

dummy data

I am trying to fix

This is the file contain new data.

That have some error.

that need to fix.

dummy data

在这个文件中,我需要更改一行"我正在尝试修复"到了#34;这超出了范围"。 并写信给mytext.txt。

任何人都可以帮我这么做吗?

2 个答案:

答案 0 :(得分:1)

试试这个:

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

答案 1 :(得分:1)

如果文件大小真的很小,这是我能想到的最简单的方法:

$text = file_get_contents('mytext.txt');
$text = str_replace('I am trying to fix', 'that is out of scope', $text);
file_put_contents('mytext.txt', $text);

布拉姆