使用php替换文本文件中的特定行? [英] Replace a particular line in a text file using php?

查看:240
本文介绍了使用php替换文本文件中的特定行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,该文件将lastname, first name, address, state, etc作为带有|分隔符的字符串存储,并且每个记录都在单独的行上.

I have a text file that stores lastname, first name, address, state, etc as a string with a | delimiter and each record on a separate line.

我需要将每条记录存储在新行中并且工作正常.但是,现在我需要能够返回并更新特定行上的名称或地址,而我无法使其正常工作.

I have the part where I need to store each record on a new line and its working fine; however, now I need to be able to go back and update the name or address on a particular line and I can't get it to work.

如何替换使用php的文本文件中的特定行?这将覆盖整个文件,而我将丢失记录.感谢您的帮助!

This how to replace a particular line in a text file using php? helped me here but I am not quite there yet. This overwrites the whole file and I lose the records. Any help is appreciated!

经过一些编辑后,现在似乎可以正常工作了.我正在调试,看是否有任何错误.

After some edit seems to be working now. I am debugging to see if any errors.

$string= implode('|',$contact);   

$reading = fopen('contacts.txt', 'r');
$writing = fopen('contacts.tmp', 'w');

$replaced = false;

while (!feof($reading)) {
 $line = fgets($reading);

  if(stripos($line, $lname) !== FALSE)  {           
if(stripos($line, $fname) !== FALSE) {  
    $line = "$string";
    $replaced = true;
}       
   }

  fwrite($writing, "$line");
  //fputs($writing, $line);
 }
fclose($reading); fclose($writing);

// might as well not overwrite the file if we didn't replace anything
if ($replaced) 
{
  rename('contacts.tmp', 'contacts.txt');
} else {
 unlink('contacts.tmp');
}   

推荐答案

似乎您有csv格式的文件. PHP可以使用fgetcsv() http://php.net/manual/de/function处理此问题.fgetcsv.php

It seems that you have a file in csv-format. PHP can handle this with fgetcsv() http://php.net/manual/de/function.fgetcsv.php

if (($handle = fopen("contacts.txt", "r")) !== FALSE) {
    $data = fgetcsv($handle, 1000, '|')
    /* manipulate $data array here */
}

fclose($handle);

这样您将获得一个可以操纵的数组.之后,您可以使用fputcsv http://www.php.net/保存文件manual/de/function.fputcsv.php

So you get an array that you can manipulate. After this you can save the file with fputcsv http://www.php.net/manual/de/function.fputcsv.php

$fp = fopen('contacts.tmp', 'w');

foreach ($data as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);

好吧,在阿萨德发表评论后,还有另一个简单的答案.只需在Append模式下打开文件 http://de3.php.net/manual /en/function.fopen.php :

Well, after the comment by Asad, there is another simple answer. Just open the file in Append-mode http://de3.php.net/manual/en/function.fopen.php :

$writing = fopen('contacts.tmp', 'a');

这篇关于使用php替换文本文件中的特定行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆