【问题标题】:How to str_replace a txt file with newlines using PHP如何使用 PHP 用换行符替换 txt 文件
【发布时间】:2020-04-03 19:27:31
【问题描述】:

我有一个包含以下 2 行的文本文件

woof
woof99

然后我有这段代码,它应该采用用户名,例如 woof 并将其取出并用任何内容替换它。

$file = fopen("../UsersProfile/".$MyUsername."/otherfiles/Following.txt","a") or die("Unable to open file");
    $content = file_get_contents("../UsersProfile/".$MyUsername."/otherfiles/Following.txt");
    $newcontent = str_replace($Username."\n", '', "$content");
    file_put_contents("../UsersProfile/".$MyUsername."/otherfiles/Following.txt", "$newcontent");
    fclose($file); 

文本文件现在看起来像这样,只有一行。

woof99

我遇到的问题是它由于某种原因无法正常工作。我相信它以前有效,但由于某种原因现在它不是。有没有更简单的方法来做到这一点? 谢谢!

编辑:我发现我需要做什么我需要做什么\r\n

【问题讨论】:

  • 您是否打开了错误记录?您是否确认file_get_contents() 成功,即不返回FALSE?您是否确认file_put_contents() 没有返回FALSE
  • file_get_contents() 正在返回数据,file_put_contents 正在工作,问题是 str_replace

标签: php file fopen str-replace


【解决方案1】:
$newcontent = str_replace($Username."\n", '', $content);

只要把这个 "$content" 变成这个 $content :D

【讨论】:

  • 这不会有什么不同,因为它们都被解释为同一个字符串。
  • $newcontent = str_replace($Username." ", '', $content);为我工作!
  • 您的代码将无法工作,因为它将换行符留在那里并且不会将其删除。结果会是\n woof99,但整个文本文件只需要是woof99,因为用户woof 已被删除
  • 很抱歉,但请正确地将您的错误代码发送给我,n将帮助您
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-13
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 2013-04-22
相关资源
最近更新 更多