覆盖文件中特定行的最佳方法是什么?我基本上想在文件中搜索字符串“@parsethis”并用其他内容覆盖该行的其余部分。
如果文件真的很大(日志文件或类似的文件)并且您愿意为了内存消耗而牺牲速度,您可以打开两个文件并基本上做到这一点杰里米·鲁滕建议使用文件而不是系统内存。
$source='in.txt';
$target='out.txt';
// copy operation
$sh=fopen($source, 'r');
$th=fopen($target, 'w');
while (!feof($sh)) {
$line=fgets($sh);
if (strpos($line, '@parsethis')!==false) {
$line='new line to be inserted' . PHP_EOL;
}
fwrite($th, $line);
}
fclose($sh);
fclose($th);
// delete old source file
unlink($source);
// rename target file to source file
rename($target, $source);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)