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


This should work for you:



<?php

    $file= "Presidents.txt";
    $lines = file($file);

    $lines[2] = str_replace("George", "Thomas", $lines[2]);
    file_put_contents($file, implode("\n", $lines) );

?>

      

+1


source


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







All Articles