搜索文件中的内容并使用PHP更改内容的最佳(最有效)方法是什么?

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了搜索文件中的内容并使用PHP更改内容的最佳(最有效)方法是什么?脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > PHP what is the best way to write data to middle of file without rewriting file3个
我有一个PHP阅读的文件.我想寻找一些以一些空格开头的行,然后是我正在寻找的一些关键词(例如,“PRoject_name:”),然后更改该行的其他部分.

目前,我处理这个的方法是将整个文件读入一个字符串变量,操作该字符串,然后将整个文件写回文件,完全替换整个文件(通过foPEn(filepath,“wb”)和fwrITe( )),但这感觉效率低下.有没有更好的办法?

更新:完成我的功能后,我有时间对其进行基准测试.我使用了1GB的大文件进行测试,但结果令人不满意:|

是的,内存峰值分配明显更小:

>标准解决方案: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'))
);

上面的脚本花了大约16秒,自定义解决方案花了大约13秒.

简历:大型文件的客户解决方案速度稍快,内存消耗更少(!!!).

此外,如果要在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,请注明来意。