Given two file handles; one which is readable and another which is writable, write one file to the other performing string-replacements on-the-fly. Imagine these files could be 10MB or so, and thus reading the *entire* file contents and doing a str_replace() is not acceptable. Use the least amount of memory possible.
Pseudo Example:
Code: Select all
function copyStreamTransformed($reader, $writer, $replacements = array()) {
while (!feof($reader) && false !== $bytes = fread($reader, 8192)) {
//here's where you'd replace $bytes using $replacements, then...
fwrite($writer, $bytes);
}
}
//Use case
$fpOut = fopen('text-file.txt', 'r');
$fpIn = fopen('replaced-file.txt', 'w');
copyStreamTransformed($fpOut, $fpIn, array('foo' => 'bar', "\r\n" => "\n"));Bear in mind that when you fread() from the reader, you may end up with half of one of your replacements tagged onto the end of the string, and the other half would come out at the start of the next read (e.g. read 1 = "some fo", read 2 = "o and more foo").
Looking forward to stealing your ideas