用php替换大文件中的字符串
我正在尝试在 PHP 中对整个文件进行字符串替换。我的文件超过 100MB,所以我必须逐行查看,并且无法使用 file_get_contents()
。对此有好的解决办法吗?
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 good solution to this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您不需要使用 PHP,我强烈建议您从命令行执行类似的操作。它是迄今为止最适合这项工作的工具,而且更容易使用。
无论如何,
sed
(流编辑器) 命令就是您正在寻找:如果您需要不区分大小写:
如果您需要在 PHP 中动态执行此操作,您可以使用
passthru()
:If you aren't required to use PHP, I would highly recommend performing stuff like this from the command line. It's by far the best tool for the job, and much easier to use.
In any case, the
sed
(Stream Editor) command is what you are looking for:If you need case-insensitivity:
If you need this to perform dynamically within PHP, you can use
passthru()
:给你:
这样称呼它:
Here you go:
Call it like this:
如果您不能直接从命令行使用 sed,因为它是一个动态任务,并且您需要从 php 调用它,那么很难获得正确的语法:您必须在搜索和替换字符串中以不同的方式转义这些字符
以下函数搜索并替换文件中的字符串而不将搜索到的字符串解释为正则表达式。因此,如果您愿意,可以搜索字符串“.*”并将其替换为“$”。
If you can't use directly sed from command line because it's a dynamic task and you need to call it from php it's difficult to get the syntax right: you must escape in different ways in the search and replacement strings these characters
The following function search and replace a string in a file without interpreting the searched string as a regular expression. So if you wanted you could search for the string ".*" and replace it with "$".
我会以更明确的方式使用“sed”,这样您就可以减少对系统的依赖。
I would have used 'sed' in a more explicit way, so you are less dependent of your system.
一次获取几行,转储变量,获取接下来的几行。
您需要确保这是正确的(尚未测试)。请参阅 PHP 文档 上的库。
棘手的部分是写回文件。我脑海中浮现的第一个想法是进行字符串替换,将新内容写入另一个文件,然后最后删除旧文件并用新文件替换它。
Get it a few lines at a time, dump the variable, get the next few lines.
You are going to want to make sure that is correct (haven't tested). See the library on PHP Documentation.
The tricky part is going to be writing back to the file. The first idea that pops into my mind is do the string replace, write the new content to another file, and then at the end, delete the old file and replace it with the new one.
像这样的东西?
something like this?