簡體   English   中英

使用php從txt文件中刪除換行符

[英]remove new line characters from txt file using php

我有 txt 文件,它的內容是這樣的

Hello  
World   
John  
play  
football  

我想在讀取這個文本文件的時候刪除換行符,但是我不知道它看起來像文件 .txt 並且它的編碼是 utf-8

只需使用帶有FILE_IGNORE_NEW_LINES標志的file功能FILE_IGNORE_NEW_LINES

file讀取整個文件,並返回包含所有文件行的數組。

默認情況下,每一行的末尾都包含換行符,但是我們可以通過FILE_IGNORE_NEW_LINES標志強制執行修整。

因此,它將很簡單:

$lines = file('file.txt', FILE_IGNORE_NEW_LINES);

結果應為:

var_dump($lines);
array(5) {
    [0] => string(5) "Hello"
    [1] => string(5) "World"
    [2] => string(4) "John"
    [3] => string(4) "play"
    [4] => string(8) "football"
}

有不同種類的換行符。 這將刪除$string中的所有3種:

$string = str_replace(array("\r", "\n"), '', $string)

如果您打算將行放入數組中,那么假設文件大小合理,則可以嘗試這樣的操作。

$file = 'newline.txt';      
$data = file_get_contents($file);   
$lines = explode(PHP_EOL, $data);  

/** Output would look like this

Array
(
    [0] => Hello  
    [1] => World   
    [2] => John  
    [3] => play  
    [4] => football  
)

*/

對於 PHP 的file()函數, FILE_IGNORE_NEW_LINES標志是要走的路。 如果您以另一種方式獲取數組,例如使用gzfile() ,請執行以下操作:

// file.txt
$lines = file('file.txt', FILE_IGNORE_NEW_LINES);

// file.txt.gz
$lines = gzfile('file.txt.gz');
$lines = array_map(function($e) { return rtrim($e, "\n\r"); }, $lines);

我注意到該文本文件在問題中的粘貼方式,每行末尾似乎都有空格字符。 我認為那是偶然的。

<?php

// Ooen the file
$fh = fopen("file.txt", "r");

// Whitespace between words (this can be blank, or anything you want)
$divider = " ";

// Read each line from the file, adding it to an output string
$output = "";
while ($line = fgets($fh, 40)) {
  $output .= $divider . trim($line);
}
fclose($fh);

// Trim off opening divider
$output=substr($output,1);

// Print our result
print $output . "\n";

暫無
暫無

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

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