Asif Iqbal
Asif Iqbal

Reputation: 1236

How to modify text file's substring using php?

This is text file's data (Presidents.txt):

George Washington 
John Adams
George Jefferson
James Madison

I want to replace George [3rd line] to Thomas without deleting or replacing all data of the text file. I want to delete or replace only George from the third line.

This is the code that I am trying:

$file = fopen("Presidents.txt","r+");
fwrite($file,'Thomas');

But output:

Thomas Washington 
John Adams
George Jefferson
James Madison

But my desired output is:

George Washington 
John Adams
Thomas Jefferson
James Madison

Is there any way to do it?

Upvotes: 2

Views: 179

Answers (2)

cari
cari

Reputation: 2302

You thinking about this?

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

Upvotes: 1

Rizier123
Rizier123

Reputation: 59701

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) );

?>

Upvotes: 1

Related Questions