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