如何从txt文件中删除不需要的空格

时间:2017-09-12 10:56:47

标签: php

我试图修改我在tokuwiki中使用的txt文件。

我在txt文件的顶部生成时间戳,如下所示:

function filecont($file,$data)
{
    $fileContents = file($file);

    array_shift($fileContents);
    array_unshift($fileContents, $data);

    $newContent = implode("\n", $fileContents);

    $fp = fopen($file, "w+");   
    fputs($fp, $newContent);
    fclose($fp);
}

我原来的txt文件如下所示:

现在当我使用我的功能时:

$txt= "Last generated: " . date("Y M D h:i:s");
filecont($file,$txt);

我得到这样的结果:

现在我不想删除====== Open IoT book ======,这可能是因为我在第一行没有空位?

但是我遇到的最严重的问题就是会产生许多我不想要的空位。

我只想将last generated放在txt文件的顶部,其他任何内容都未触动

3 个答案:

答案 0 :(得分:2)

我测试了您的代码并通过更改行删除了额外的换行符:

$fileContents = file($file);

$fileContents = file($file, FILE_IGNORE_NEW_LINES);

添加FILE_IGNORE_NEW_LINES标志会停止向每个元素/行添加换行符。

http://php.net/manual/en/function.file.php

我还删除了array_unshift(),它离开了' ====== Open IoT book ======'在文件中。

所以我的最终功能看起来像这样:

function filecont($file,$data)
{
    $fileContents = file($file, FILE_IGNORE_NEW_LINES);

    //array_shift($fileContents); Removed to preserve '====== Open IoT book ======' line.
    array_unshift($fileContents, $data);

    $newContent = implode("\n", $fileContents);

    $fp = fopen($file, "w+"); 
    fclose($fp);
}

答案 1 :(得分:1)

可能只是删除此行

array_shift($fileContents);

解决你的问题?

答案 2 :(得分:1)

当你获得文件元素时,你需要检查Last generated:是否是你的第一行或不符合它你需要使用array_shift

$fileContents = file($file);
  if(stripos($fileContents[0],"Last generated:") !== false)
  {
    array_shift($fileContents); //if found use shift
  }

    array_unshift($fileContents, $data);
相关问题