【问题标题】:PHP Add or Edit line in text FilePHP 在文本文件中添加或编辑行
【发布时间】:2017-04-24 14:14:52
【问题描述】:

我正在尝试搜索文本文件,如果一行包含特定的密钥 ID,我想更新整行,如果不添加新行。

所以基于这个文本文件:

admin,1234,ID1345,NW
staff,1325,ID1001,NE
staff,2157,ID2003,SW
staff,8519,ID3001,NS

我想搜索ID1345,然后只更新该行,其他行保持原样。如果没有行包含ID1345,则在文本文件中添加一个新行。

到目前为止,我得到了:

$search = 'ID1345';
$result = 'admin,6698,ID1345,OP';

$reading = fopen('myfile', 'r');
$writing = fopen('myfile.tmp', 'w');
$replaced = false;

while (!feof($reading)) {
  $line = fgets($reading);
  if (stristr($line, $search)) {
    $line = "$result\n";
    $replaced = true;
  }
  fputs($writing, $line);
}

if (!$replaced) fputs($writing, "$result\n");
fclose($reading); fclose($writing);
rename('myfile.tmp', 'myfile');

这似乎适用于查找和替换,但如果该行不存在,它会不断添加它,而不仅仅是一次。

我知道这是因为if (!$replaced) 行,但我不知道该怎么做。

上面的例子很小,但文件中可能有几千个条目..

谢谢

【问题讨论】:

  • 旁注:您不为此使用数据库是否有特殊/特定原因?文本文件的工作量很大。
  • 可能指针不在正确的位置。测试一下。在fclose() 下移动if($repl..) 行并使用if($repl..) file_put_contents('myfile.tmp',"$result\n",FILE_APPEND);
  • 你的意思是当你只运行一次这个脚本时它会继续添加它,还是只在你使用同一个文件运行多次时?如果是第二种情况,也许它可能是无法识别的换行符?手册上建议使用 wb 而不是 wfopen 以实现可移植性和新行字符..
  • @Fred-ii- 不幸的是,我无法访问该系统上的任何数据库。我只有文本文件。

标签: php file replace find add


【解决方案1】:
function file_properties($fileProperties) {
$result = array();
$lines = split("\n", $fileProperties);
$key = "";
$isWaitingOtherLine = false;

foreach($lines as $i=>$line) {
    if(empty($line) || (!$isWaitingOtherLine && strpos($line,"#") === 0)) continue;

    if(!$isWaitingOtherLine) {
        $key = substr($line,0,strpos($line,'='));
        $value = substr($line,strpos($line,'=') + 1, strlen($line));
    } else {
        $value .= $line;
    }

    /* Check if ends with single '\' */
    if(strrpos($value,"\\") === strlen($value)-strlen("\\")) {
        $value = substr($value, 0, strlen($value)-1)."\n";
        $isWaitingOtherLine = true;
    } else {
        $isWaitingOtherLine = false;
    }

    $result[$key] = $value;
    unset($lines[$i]);
}

return $result;

}

这将读取和写入具有任何扩展名的文件,如 Laravel 中的 .env 或 Java 中的任何 *.properties

【讨论】:

    猜你喜欢
    • 2013-03-04
    • 1970-01-01
    • 2014-06-10
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多