File_get_contents and file_put_contents with large files
I'm trying to get the content of a file, replace some parts of it with regex and preg_replace, and save it to another file:
$content = file_get_contents('file.txt', true);
$content_replaced = preg_replace('/\[\/m\]{1}\s+(\{\{.*\}\})\s+[\x{4e00}-\x{9fa5}]+/u', 'replaced text', $contents);
if ($content_replaced) {
file_put_contents('file_new.txt', $content_replaced);
echo "Successful!";
}
else {
echo "Some error ocurred";
}
this code snippet works fine with small files, but when I try to create a source file which is about 60MB, it just keeps giving me the message "Some error occured".
Any suggestions are greatly appreciated.
Update. No errors in logs, memory limit is set to 1024M
I'm sure you'll hit the regex constraint. Heck, a while ago I hit the 1000 character limit ... with 60MB of input. The bet is that you are probably really simple templates. I'll try to at least simplify it as much as possible by making it jagged with .*?
instead .*
, if possible.
For more information, just check the return value preg_last_error()
.
source to share