【问题标题】:Php replace line in a file txtphp替换文件txt中的行
【发布时间】:2014-02-04 16:40:13
【问题描述】:
<?php
$myFile = "/home/user1/www/cgi-bin/mytext.txt";
$lines = file($myFile);
$lines[3] = $_POST['title'];
file_put_contents($myFile , implode("\n", $lines));
?>

我只会更改“第 3 行”而不更改其他行,哪里出错了?

我已经输入了 mytext.txt:

  • line1 -------------------------------------
  • 第 2 行 #WORD:
  • 第 3 行更改
  • 第4行
  • 第5行你好
  • line6 PIPPO
  • line7 FOO
  • line8 凯特欧文

午餐脚本后,这是输出 mytext.txt:

  • line1 -------------------------------------
  • 第2行
  • 第 3 行 #WORD:
  • 第4行
  • 第 5 行更改
  • 第6行
  • line7 $_POST['title']
  • 第8行你好
  • 第9行
  • 第10行皮波
  • 第11行
  • 第 12 行 FOO
  • 第13行
  • line14 凯特欧文

【问题讨论】:

    标签: php replace line


    【解决方案1】:

    您可以在file() 中使用FILE_IGNORE_NEW_LINES 常量,或者不要使用更多换行符:

    file_put_contents($myFile , implode('', $lines));
    

    或者只是这个,因为它会为你内爆:

    file_put_contents($myFile , $lines);
    

    但您需要在此处添加换行符:

    $lines[3] = $_POST['title'] . "\n";
    

    所以这可能是最直接的:

    $lines = file($myFile, FILE_IGNORE_NEW_LINES);
    $lines[3] = $_POST['title'];
    file_put_contents($myFile , implode("\n", $lines));
    

    【讨论】:

      【解决方案2】:

      你可以毫无问题地使用 str_replace 函数

      看看这个

       str_replace('line3 CHANGETHIS', 'line3 #WORD:', $file_content)
      

      然后将函数结果保存到文件中

      【讨论】:

      • 我需要将第 3 行替换为我的表单 html 中的值 $_POST['title']
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-04
      • 2022-01-19
      相关资源
      最近更新 更多