string replace in a large file with php

后端 未结 6 1889
借酒劲吻你
借酒劲吻你 2020-12-09 12:41

I am trying to do a string replace for entire file in PHP. My file is over 100MB so I have to go line by line and can not use file_get_contents(). Is there a

6条回答
  •  轮回少年
    2020-12-09 13:02

    something like this?

    $infile="file";
    $outfile="temp";
    $f = fopen($infile,"r");
    $o = fopen($outfile,"a");
    $pattern="pattern";
    $replace="replace";
    if($f){
         while( !feof($f) ){
            $line = fgets($f,4096);
            if ( strpos($pattern,"$line") !==FALSE ){
                $line=str_replace($pattern,$replace,$line);
            }
            fwrite($o,$line);
         }
    }
    fclose($f);
    fclose($o);
    rename($outfile,$infile);
    

提交回复
热议问题