[英]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
// 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.