简体   繁体   English

PHP逐行读取大文件并替换字符串

[英]PHP read a large file line by line and string replace

I'd like to read a large file line by line, perform string replacement and save changes into the file, IOW rewriting 1 line at a time. 我想逐行读取一个大文件,执行字符串替换并将更改保存到文件中,IOW一次重写1行。 Is there any simple solution in PHP/ Unix? 在PHP / Unix中是否有任何简单的解决方案? The easiest way that came on my mind would be to write the lines into a new file and then replace the old one, but it's not elegant. 我想到的最简单的方法是将这些行写到一个新文件中,然后替换旧文件,但这并不好。

I think there're only 2 options 我认为只有两种选择

  1. Use memory 使用记忆

Read, replace then store the replaced string into memory, once done, overwrite the source file. 读取,替换,然后将替换后的字符串存储到内存中,完成后,覆盖源文件。

  1. Use tmp file 使用tmp文件

Read & replace string then write every line immediately to tmp file, once all done, replace original file by tmp file 读取和替换字符串,然后将每一行立即写入tmp文件,一旦完成,请用tmp文件替换原始文件

The #1 will be more effective because IO is expensive, use it if you have vast memory or the processing file is not too big. #1会更有效,因为IO昂贵,如果您有大量内存或处理文件不太大,请使用它。

The #2 will be a bit slow but be quite stable even on large file. #2会有点慢,但即使在大文件上也相当稳定。

Of course, you may combine both way by writing replaced string by chunk of lines to file (instead of just by line ) 当然,你可以通过写串代替由线块结合两种方式文件(而不是仅仅通过线

There're the simplest, most elegant ways I can think out. 我可以思考出最简单,最优雅的方法。

It seems it's not such a bad solution to use the temporary file in most cases. 在大多数情况下,使用临时文件似乎不是一个糟糕的解决方案。

$f='data.txt';
$fh=fopen($f,'r+');
while (($l=fgets($fh))!==false) file_put_contents('tmp',clean($l),FILE_APPEND);
fclose($f);
unlink($f); 
rename('tmp',$f);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM