脚本宝典收集整理的这篇文章主要介绍了搜索文件中的内容并使用PHP更改内容的最佳(最有效)方法是什么?,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
目前,我处理这个的方法是将整个文件读入一个字符串变量,操作该字符串,然后将整个文件写回文件,完全替换整个文件(通过foPEn(filepath,“wb”)和fwrITe( )),但这感觉效率低下.有没有更好的办法?
是的,内存峰值分配明显更小:
>标准解决方案:1,86 GB
>自定义解决方案:653 KB(4096字节缓冲区)
ini_set('memory_limit',-1); file_put_contents( 'test.txt',str_replace('the','teh',file_get_contents('test.txt')) );
简历:大型文件的客户解决方案速度稍快,内存消耗更少(!!!).
此外,如果要在Web服务器环境中运行此选项,则自定义解决方案会更好,因为许多并发脚本可能会占用系统的整个可用内存.
原答案:
唯一要记住的是,以符合文件系统块大小的块读取文件,并将内容或修改后的内容写回临时文件.完成处理后,使用rename()覆盖原始文件.
注意:在linux系统上,您可以使用以下命令获取文件系统块大小:
sudo dumpe2fs /dev/yourdev | grep 'Block size'
我得到了4096
功能如下:
function freplace($seArch,$replace,$filename,$buffersize = 4096) { $fd1 = fopen($filename,'r'); if(!is_resource($fd1)) { die('error opening file'); } // the tempfile can be anywhere but on the same partition as the original $tmpfile = tempnam('.',uniqid()); $fd2 = fopen($tmpfile,'w+'); // we Store len(search) -1 chars From the end of the buffer on each loop // this is the maximum chars of the search string that can be on the // border between two buffers $tmp = ''; while(!feof($fd1)) { $buffer = fread($fd1,$buffersize); // prepend the rest from last one $buffer = $tmp . $buffer; // replace $buffer = str_replace($search,$buffer); // store len(search) - 1 chars from the end of the buffer $tmp = substr($buffer,-1 * (strlen($search)) + 1); // write processed buffer (minus rest) fwrite($fd2,$buffer,strlen($buffer) - strlen($tmp)); }; if(!empty($tmp)) { fwrite($fd2,$tmp); } fclose($fd1); fclose($fd2); rename($tmpfile,$filename); }
像这样称呼它:
freplace('foo','bar','test.txt');
以上是脚本宝典为你收集整理的搜索文件中的内容并使用PHP更改内容的最佳(最有效)方法是什么?全部内容,希望文章能够帮你解决搜索文件中的内容并使用PHP更改内容的最佳(最有效)方法是什么?所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。