开发者

Find and edit text files via PHP

开发者 https://www.devze.com 2022-12-13 05:08 出处:网络
Let say a text fi开发者_StackOverflowle contain Hello everyone, My name is Alice, i stay in Canada.

Let say a text fi开发者_StackOverflowle 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);


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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号