大文件的file_get_contents和file_put_contents [英] file_get_contents and file_put_contents with large files
问题描述
我试图获取文件内容,用正则表达式和preg_replace替换它的一些部分,并保存到另一个文件中:
$ content = file_get_contents('file.txt',true);
$ content_replaced = preg_replace('/ \ [\ / m \] {1} \s+(\ {\ {。* \} \})\s + [\ x {4e00} -\x {9fa5}] + / u','replace text',$ contents);
if($ content_replaced){
file_put_contents('file_new.txt',$ content_replaced);
回声成功!;
}
else {
echo发生了一些错误;
}
这段代码可以很好地处理小文件,但是当我尝试原始文件,这是大约60Mb,它只是不断给我一个消息一些错误发生。
任何建议,不胜感激。
更新。在日志中没有错误,内存限制被设置为1024M
我敢肯定你正在碰到一些正则表达式的限制。哎呀,前一段时间,我打了一个极限 1000字符。用60Mb的输入我敢打赌,你可能会遇到正则表达式的限制,也有非常简单的模式。我会尽量至少简化它,使其不符合。*?
而不是。*
如果可能的话。
要获得更多信息,只需检查 preg_last_error()
。
I'm trying to get file contents, replace some parts of it using regular expressions 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 piece of code works fine with small files, but when I try the original file, which is about 60Mb, it just keeps giving me a message "Some error ocurred".
Any suggestions are greatly appreciated.
Update. No errors in the logs, memory limit is set to 1024M
I'm pretty sure you're hitting some regex limit. Heck, some time ago I hit a limit with 1000 chars... with 60Mb of input I bet you will likely hit regex limits everywhere also with really simple patterns. I will try at least to simplify it as much as possible, making it ungreedy with .*?
instead of .*
if possible.
To get more information, just check the return value of preg_last_error()
.
这篇关于大文件的file_get_contents和file_put_contents的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!