string replace in a large file with php
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:
sed s/search/replace oldfilename > newfilename
If you need case-insensitivity:
sed s/search/replace/i oldfilename > newfilename
If you need this to perform dynamically within PHP, you can use passthru()
:
$output = passthru("sed s/$search/$replace $oldfilename > $newfilename");
Here you go:
function replace_file($path, $string, $replace)
{
set_time_limit(0);
if (is_file($path) === true)
{
$file = fopen($path, 'r');
$temp = tempnam('./', 'tmp');
if (is_resource($file) === true)
{
while (feof($file) === false)
{
file_put_contents($temp, str_replace($string, $replace, fgets($file)), FILE_APPEND);
}
fclose($file);
}
unlink($path);
}
return rename($temp, $path);
}
Call it like this:
replace_file('/path/to/fruits.txt', 'apples', 'oranges');