How can I change a substring of a text file using php?
This is text data (Presidents.txt):
George Washington
John Adams
George Jefferson
James Madison
I want to replace George [3rd line] with Thomas without deleting or replacing all text file data. I only want to remove or replace George from the third line.
This is the code I'm trying to do:
$file = fopen("Presidents.txt","r+");
fwrite($file,'Thomas');
But the conclusion is:
Thomas Washington
John Adams
George Jefferson
James Madison
But my desired result is:
George Washington
John Adams
Thomas Jefferson
James Madison
Is there a way to do this?
+3
source to share
2 answers
Do you think about it?
$handle = fopen("Presidents.txt", "r");
$file="";
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo $line;
if($line=="George Jefferson\r\n") {
$line="Thomas Jefferson\r\n";
}
$file .= $line;
}
}
fclose($handle);
$handle = fopen("Presidents.txt", "w+");
fwrite($handle,$file);
fclose($handle);
+1
source to share