2015-06-10 50 views
3

我希望能夠寫入文件並始終在該行寫入。寫入文件中的特定行

1 Hello 
2 How are you 
3 Good 
4 I see 
5 Banana 
6 End 

使用功能:

function filewriter($filename, $line, $text,$append) { 
} 

所以追加=增加而不會覆蓋線路,這是可選的,因爲它會默認爲追加

所以追加:

filewriter ("bob.txt", 2, "Bobishere", true) or filewriter ("bob.txt", 2, "Bobishere") 

輸出:

1 Hello 
2 Bobishere 
3 How are you 
4 Good 
5 I see 
6 Banana 
7 End 

,但如果他們不追加它看起來像這樣: 的FileWriter( 「bob.txt」,2, 「Bobishere」,假)

輸出:

1 Hello 
2 Bobishere 
3 Good 
4 I see 
5 Banana 
6 End 

我只有設法弄清楚如何覆蓋文件或添加到文檔的末尾。

什麼功能看起來像目前:

function filewriter($filename,$line,$text,$append){ 
    $current = file_get_contents($filename); 
    if ($append) 
    $current .= $line; 
    else 
    $current = $line; 
    file_put_contents($file, $current); 
} 
+0

向我們顯示您的代碼,我們可以查找錯誤。 – Sablefoste

+0

完成!對不起,我只是覺得它沒用:x –

+0

爲什麼所有的標籤?這裏只有php –

回答

0

讓我們來重寫你的函數:

function filewriter($filename,$line,$text,$append){ 
    $current = file_get_contents($filename); 

    //Get the lines: 
    $lines = preg_split('/\r\n|\n|\r/', trim($current)); 

    if ($append) 
    { 
     //We need to append: 
     for ($i = count($lines); $i > $line; $i--) 
     { 
      //Replace all lines so we get an empty spot at the line we want 
      $lines[$i] = $lines[i-1]; 
     } 

     //Fill in the empty spot: 
     $lines[$line] = $text; 
    } 
    else 
     $lines[$line] = $text; 

    //Write back to the file. 
    file_put_contents($file, $lines); 
} 

這個系統背後的邏輯是:

我們得到了清單:

[apple, crocodile, door, echo] 

我們要在第2行我們會首先做插入bee,是將所有的元素以後,線路2:

1: apple 
2: crocodile 
3: door 
4: echo 
5: echo //==> We moved 'echo' 1 spot backwards in the array 

下一頁:

1: apple 
2: crocodile 
3: door 
4: door //==> We moved 'door' 1 spot backwards in the array 
5: echo 

然後:

1: apple 
2: crocodile //==> This is a useless spot now, so we can put "bee" here. 
3: crocodile //==> We moved 'crocodile' 1 spot backwards in the array 
4: door 
5: echo 

然後我們把「蜜蜂」放在我們想要的行上:

1: apple 
2: bee //==> TADA! 
3: crocodile 
4: door 
5: echo 

警告:在PHP陣列是從零開始的,所以,第一行是行0。在使用上述功能時記住這一點!

+0

由於操作系統和FS的限制,向OP解釋他如何不能將字節插入文件,僅覆蓋它們,而不重寫整個文件本身可能是一個好主意。 –

相關問題