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

时间:2013-04-02 12:21:48

标签: php fopen fclose

我正在尝试从文本文件中删除/编辑部分文本,比如我的文本文件中有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);

4 个答案:

答案 0 :(得分:2)

您可以将其缩短为:

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

答案 1 :(得分: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

答案 2 :(得分:0)

如果您的文本文件中只有10行,那么除非它们是非常长的行,否则您将更改更改内容所需的物理I / O量(磁盘只能读/写一个数据一次是物理扇区 - 512字节的日子早已不复存在。)

是的,您可以通过仅编写已更改的扇区来修改大文件 - 但这需要您使用相同大小的内容替换数据以防止出现帧错误(在PHP中使用fopen with mode c +,fgets / fseek / fwrite / ftell,fclose)。

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

答案 3 :(得分: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);

我根据自己的理解添加了解决方案,希望它会有所帮助!!!