使用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读取整个文件并返回一个包含所有文件行的数组。

默认情况下,每一行的末尾都包含换行符,但我们可以通过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";

对于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);