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
在这个文件中,我需要将"我正在尝试修复"一行更改为"超出范围"。并写入mytext.txt。
有人能帮我做这件事吗?
试试这个:
$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');
}
如果文件大小真的这么小,这是我能想到的最简单的方法:
$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);
Blam