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?

Comments

Is it necessary to use PHP? If you have access to the command line, you could use the sed command to perform this same function, probably with a much less of a headache. If it needs to be automated, you can make a shell script that runs on cron.

Written by Dominic Barnes

Agreed, this is something for the command line, not PHP.

Written by Mike

Accepted Answer

If you aren't required to use PHP, I would highly recommend performing stuff like this from the command line. It's byfar the best tool for the job, and much easier to use.

In any case, the sed command is what you are looking for:

sed s/search/replace oldfilename > newfilename

If you need case-insensitivity:

sed -i s/search/replace oldfilename > newfilename

If you need this to perform dynamically within PHP, you can use passthru():

$output = passthru("sed s/$search/$replace $oldfilename > $newfilename");
Written by Dominic Barnes
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki