PHP中替换文件内容
我需要一个类似于 preg_replace 的函数,但我需要它而不是字符串处理文件/文件内容。
I need a function just like preg_replace but instead of strings I need it to work with files / file content.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可以这样做:
You can do:
@codaddict 的答案对于小文件来说已经足够了(如果文件的大小低于 MiB,我将如何实现它)。然而,它会消耗大量内存,因此在读取大文件时应该小心。
如果您想要一个更内存友好的版本,您可以使用 流过滤器...
因此,您可以附加任意流过滤器。过滤器的名称决定了参数:
或者对于数组,
显然这是一个非常简单的示例(并且没有进行大量错误检查),但它允许您执行如下操作:
这将使内存使用量保持在非常低的水平处理潜在的巨大(GiB 或 TiB)文件...
哦,另一个很酷的事情是它可以内联编辑不同的流类型。我的意思是,您可以从 HTTP 流中读取、内联编辑以及写入文件流。它非常强大(因为你可以链接这些过滤器)......
@codaddict's answer is quite sufficent for small files (and would be how I would implement it if the size of the file was under a MiB). However it will eat up a ton of memory, and as such you should be careful when reading large files.
If you want a much more memory friendly version, you could use stream filters...
So, then you can append an arbitrary stream filter. The filter's name determines the arguments:
or for arrays,
Obviously this is a really simple example (and doesn't do a lot of error checking), but it allows you to do something like this:
And that will keep memory usage very low while processing potentially huge (GiB or TiB) files...
Oh, and the other cool thing, is it can inline edit differing stream types. What I mean by that is that you can read from a HTTP stream, edit inline, and write to a file stream. It's quite powerful (as you can chain these filters)...