如何从php中的文本文件替换文本的某些部分

问题描述 投票:1回答:5

我正在尝试从文本文件中删除/编辑文本的某些部分,例如如果我的文本文件中有10行,那么我想编辑第5行或删除第3行而不影响任何其他行。

当前我在做什么1.打开文本文件并读取php变量中的数据2.完成对该变量的编辑3.删除文本文件的内容。4.在上面写新内容

但是有什么方法可以做而不删除整个内容或仅编辑那些内容吗?

我当前的代码是这样的

$file = fopen("users.txt", "a+");
$data = fread($file, filesize("users.txt"));
fclose($file);
$newdata = str_replace($old, $new, $data);
file_put_contents("users.txt", "");
$file = fopen("users.txt", "a+");
fwrite($file, $newdata);
fclose($file);
php fopen fclose
5个回答
2
投票

您可以将其缩短为:

$data = file_get_contents("users.txt");
$newdata = str_replace($old, $new, $data);
file_put_contents("users.txt", $newdata);

0
投票

您可以在每一行上工作:

$lines = file("users.txt");
foreach($lines as &$line){
  //do your stufff 
  // $line is one line
  //
}
$content = implode("", $lines);
//now you can save $content like before

0
投票

如果文本文件中只有10行,那么除非它们很长,否则您将更改更改内容所需的物理I / O数量(磁盘将只读取/写入一个数据< 一次扇区-512byte扇区的日子早已过去)。

是的,您可以通过仅写入已更改的扇区来修改大文件-但这要求您用相同大小的数据替换数据,以防止发生帧错误(在PHP中,使用copen模式,fgets / fseek / fwrite模式的fopen / ftell,fclose)。

真正的核心答案是停止在文本文件中存储多值数据,并使用DBMS(这也解决了并发性问题。)>


0
投票
$str = ''; $lines = file("users.txt"); foreach($lines as $line_no=>$line_txt) { $line_no += 1; // Start with zero //check the line number and concatenate the string if($line_no == 5) { // Append the $str with your replaceable text } else{ $str .= $line_txt."\n"; } } // Then overwrite the $str content to same file // i.e file_put_contents("users.txt", $str);

0
投票
要回答这个问题,不,你不能。
© www.soinside.com 2019 - 2024. All rights reserved.