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

+2


source to share


3 answers


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()

.

+2


source


I had max / limit problems with file_put_contents

.



I don't know what the limitations might be, but using it fwrite

solved my problems and I put the bottle down.

+4


source


You are probably running out of memory. What has memory_limit set? (phpinfo () will tell you). You might be able to increase the memory limit, for example:

ini_set('memory_limit','128M');

      

+2


source







All Articles