UFOman
UFOman

Reputation:

Find and edit text files via PHP

Let say a text file contain

Hello everyone, My name is Alice, i stay in Canada.

How do i use php to find "Alice" and replace it with "John".

    $filename = "C:\intro.txt";
    $fp = fopen($filename, 'w');
    //fwrite($fp, $string);
    fclose($fp);

Upvotes: 1

Views: 6142

Answers (3)

ghostdog74
ghostdog74

Reputation: 342373

If its a big file, use iteration instead of reading all into memory

$f = fopen("file","r");
if($f){
    while( !feof($f) ){
        $line = fgets($f,4096);
        if ( (stripos($line,"Alice")!==FALSE) ){
            $line=preg_replace("/Alice/","John",$line);
        }
        print $line;
    }
    fclose($f);
}

Upvotes: 0

Matteo Riva
Matteo Riva

Reputation: 25060

$contents = file_get_contents($filename);
$new_contents = str_replace('Alice', 'John', $contents);
file_put_contents($filename, $new_contents);

Upvotes: 10

Yacoby
Yacoby

Reputation: 55445

Read the file into memory using fread(). Use str_replace() and write it back.

Upvotes: 1

Related Questions