簡體   English   中英

PHP:如何從文本文件中刪除最后一個換行符?

[英]PHP: how to remove the last line break from the text file?

在學校工作中,我使用PHP為我所在城市的虛構太空博物館建造了一個網站。 它有一個數據包含和數據咨詢系統,但我有一個問題,我想知道如何解決咨詢:如何從文件中刪除最后一個換行符?

數據包含

在網站的限制區域,我有一個HTML5表單,其中包含5個字段(名稱,地址,電話號碼,性別和訪問過的展覽),它們通過方法POST將數據發送到PHP中的函數,該函數將其寫入給定的txt文件通過使用fwrite命令:

fwrite ($pointer, "$name | $addres | $telephone | $sex | $exhibitions " .PHP_EOL);

如您所見,它在txt文件中寫入在表單上輸入的數據,以及換行符。 指針是fopen用來打開我需要工作的文件的變量。 輸出示例:

MárcioAguiar| Belmiro Braga Street | 1234-5678 | M | 太陽系行星
Joana Tobias | Santos Dummont Avenue | 8765-4321 | F | 黑洞,衛星

數據咨詢

然后是咨詢系統。 它有一個循環,一直運行直到文件結束。 在這個循環中有一個名為$buffer的變量,每次都獲取一行txt文件。 然后explode d來創建一個名為$lines[$counter]的數組。 為了很好地打印它,我使用array_combine ,其中我將另一個數組( $keys )上的字段名稱連接到$lines[$counter]寫入的值,並將其歸結為$combined[$counter] 然后循環結束,我在<pre></pre>使用print_r來查看以$combined編寫的數據,同時保留HTML否則將忽略的空格和符號。 這是代碼:

$keys = array ("Name", "Address", "Telephone", "Sex", "Visited exhibition");
for ($counter=0;!feof($reader);$counter++){
    $buffer = fgets($reader);
    $lines[$counter] = explode(" | ", $buffer);
    $combined[$counter] = array_combine($keys, $lines[$counter]);
}
echo "<pre>";
print_r($combined);
echo "</pre>";

輸出示例:

  Array ( [0] => Array ( [Name] => Márcio Aguiar [Address] => Belmiro Braga Street [Telephone] => 1234-5678 [Sex] => M [Visited exhibitions] => Planets of Solar System ) [1] => Array ( [Name] => Joana Tobias [Address] => Santos Dummont Avenue [Telephone] => 8765-4321 [Sex] => F [Visited exhibitions] => Black Holes, Satellites ) [2] => ) 

在這里你可以看到一個2數組被創建為空白。 它是由最后一行引起的,它只包含上面表格插入的換行符。 我需要刪除最后一個換行符,只有那個,但不知道如何。 我想知道! 當執行到達array_combine ,不知道導致錯誤的array_combine ,因為需要兩個數組具有相同數量的元素,並且2是空白的。 這里的錯誤:

警告:array_combine():這兩個參數在第60行的E:\\ Aluno \\ Documents \\ Wamp \\ www \\ trab_1 \\ area_restrita \\ consulta.php中應具有相同數量的元素

原始答案:

要從任何文本中刪除尾部換行符,可以使用trim() ,但在您的情況下, 您只需要在 追加模式下使用 fopen

$handle = fopen("/path/to/file", "a");

然后擺脫PHP_EOL

fwrite ($pointer, "$name | $addres | $telephone | $sex | $exhibitions");

編輯:你是對的,追加不會附加到新行。 我誤解了。 所以你可以像我之前提到的那樣使用trim()。 我使用file_get_contents()file_put_contents()創建了一個快速示例,它似乎可以執行您想要的操作:

<?php

$file = 'test.txt';

// Set existing contents (for testing sake)
$orig_contents = "bob | 123 fake street | 1234567890 | yes, please | no\n";
$orig_contents .= "bob | 123 fake street | 1234567890 | yes, please | no\n";
$orig_contents .= "bob | 123 fake street | 1234567890 | yes, please | no\n";
$orig_contents .= "bob | 123 fake street | 1234567890 | yes, please | no\n";
file_put_contents($file, $orig_contents);

// Here is how you could add a single new line with append mode
// Notice the trailing \n
file_put_contents($file, "billy | 456 fake street | 2345678901 | no | yes\n", FILE_APPEND);

// Get contents from the file and remove any trailing line breaks
$contents = trim(file_get_contents($file));

$keys = array ("Name", "Address", "Telephone", "Sex", "Visited exhibition");

// Explode based on the new line character
$lines = explode("\n", $contents);

foreach ($lines as $line) {
    $values = explode(" | ", $line);
    $combined[] = array_combine($keys, $values);
}

print_r($combined);

這打印:

Array
(
    [0] => Array
        (
            [Name] => bob
            [Address] => 123 fake street
            [Telephone] => 1234567890
            [Sex] => yes, please
            [Visited exhibition] => no
        )

    [1] => Array
        (
            [Name] => bob
            [Address] => 123 fake street
            [Telephone] => 1234567890
            [Sex] => yes, please
            [Visited exhibition] => no
        )

    [2] => Array
        (
            [Name] => bob
            [Address] => 123 fake street
            [Telephone] => 1234567890
            [Sex] => yes, please
            [Visited exhibition] => no
        )

    [3] => Array
        (
            [Name] => bob
            [Address] => 123 fake street
            [Telephone] => 1234567890
            [Sex] => yes, please
            [Visited exhibition] => no
        )

    [4] => Array
        (
            [Name] => billy
            [Address] => 456 fake street
            [Telephone] => 2345678901
            [Sex] => no
            [Visited exhibition] => yes
        )

)

問題在於您正在閱讀文件的方式。 在從文件中讀取之前,您正在測試EOF。 但是,當你在文件末尾嘗試閱讀時, feof()將不會成立。

相反,您應該測試fgets()是否返回一行。

for ($counter = 0; $buffer = fgets($reader); $counter++) {
    $lines[$counter] = explode(" | ", $buffer);
    $combined[$counter] = array_combine($keys, $lines[$counter]);
}

DEMO

為了進一步解釋,假設您有一個包含一行的文件。 $counter0 ,你調用feof() ,它返回false 然后你讀取第一行,並將其添加到$lines$combined 然后你增加$counter並返回循環的開頭。

$counter1 ,你調用feof() 它仍然不是真的,因為你還沒有嘗試在文件的末尾閱讀。 然后你嘗試讀取下一行,但是那里沒有行, fgets返回false並將其分配給$buffer 通過explode()將其視為空字符串,因此您向$lines$combined添加一個空數組。 然后你增加$counter並返回循環的開頭。

然后你調用feof() ,這次它返回true因為你試圖在上一次迭代的文件末尾讀取。 所以循環結束了。

正如您從上面所看到的,即使文件只有1行,您最終會在數組中輸入2個條目,因為直到您讀得太多之后才測試EOF。

如果你想擺脫從db($ res)中提取的數據中的最后一個換行符,你可以使用以下代碼片段

for ($i=0; $i <count($res); $i++) {

    // If this is not last item then add items separated by line break
    if($i+1 < count($res)) {
        file_put_contents("file.txt", $res[$i].PHP_EOL, FILE_APPEND);
    }
    // If this is the last item, then don't append the final line break
    else {
        file_put_contents("file.txt", $res[$i], FILE_APPEND);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM