2017-09-12 74 views
0

我试图修改我在tokuwiki中使用的txt文件。如何从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 ======,这可能是因为我在第一行中没有空白空间?

但是我遇到的最糟糕的问题就是生成了许多不需要的空白空间。

我只希望在TXT文件和其他任何触及顶部得到last generated

回答

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(),这会在文件中留下'======打开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); 
} 
+0

工作过,谢谢。 PS我甚至不知道有一个FILE_IGNORE_NEW_LINES大声笑 – Godhaze

+0

没问题。很高兴我能帮上忙。 – Springie

1

也许只是删除这一行

array_shift($fileContents); 

解决问题了吗?

+0

我以前尝试过,但我有语法错误!不知道为什么 – Godhaze

1

,当你得到你需要检查Last generated:是否是你的第一个行或不accordong它宇需要使用array_shift

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

    array_unshift($fileContents, $data); 
+0

这个if语句也帮助了我,谢谢! – Godhaze