您可以在较小的文件上使用一种方法,该文件可以两次装入您的内存:
$data = file('myfile'); // reads an array of linesfunction replace_a_line($data) { if (stristr($data, 'certain word')) { return "replaement line!n"; } return $data;}$data = array_map('replace_a_line',$data);file_put_contents('myfile', implode('', $data));
快速说明,PHP> 5.3.0支持lambda函数,因此您可以删除命名的函数声明并将映射缩短为:
$data = array_map(function($data) { return stristr($data,'certain word') ? "replacement linen" : $data;}, $data);
从理论上讲,您可以使它成为单个(很难理解)的php语句:
file_put_contents('myfile', implode('', array_map(function($data) { return stristr($data,'certain word') ? "replacement linen" : $data; }, file('myfile'))));
您应该对较大的文件使用另一种(较少占用内存的方法):
$reading = fopen('myfile', 'r');$writing = fopen('myfile.tmp', 'w');$replaced = false;while (!feof($reading)) { $line = fgets($reading); if (stristr($line,'certain word')) { $line = "replacement line!n"; $replaced = true; } fputs($writing, $line);}fclose($reading); fclose($writing);// might as well not overwrite the file if we didn't replace anythingif ($replaced) { rename('myfile.tmp', 'myfile');} else { unlink('myfile.tmp');}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)