使用PHP从txt文件中删除换行符

13

我有一个txt文件,它的内容像这样:

Hello  
World   
John  
play  
football  
我想在读取此文本文件时删除换行符,但我不知道它是什么样子的, 该文件是.txt格式且编码为utf-8。
我想删除读取这个文本文件时的换行字符,但是我不知道这个换行字符长什么样子, 这个文件的格式是 .txt,编码为 utf-8。

Mira,你想用空白替换还是其他类型的空格? - ghoti
5个回答

20

只需使用带有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"
}

4
你还可以使用这个:$lines = file('file.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)。这样可以跳过空的新行! - Derk Jan Speelman

14

换行符有不同的种类。这将从$string中删除所有3种类型的换行符:

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

有2种还是3种? - Mira
1
@Mira,有3种情况(\r\n\r\n),而我回答中的脚本可以处理这3种情况。 - Alex Turpin

6
如果您要将这些行放入数组中,并且假设文件大小合理,您可以尝试以下方法。
$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  
)

*/

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

0

我注意到在问题中粘贴的方式,这个文本文件似乎在每行末尾都有空格字符。我会假设那是意外的。

<?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";

当任何单词超过40个字节时,结果将无效(更不用说它仅适用于每行一个单词)。如果只需要修剪右侧,则“trim”不是一个好选择,可以使用rtrim。不要忘记第二个参数,即字符掩码。默认情况下,它会修剪:空格、制表符、换行符、回车符、空字节和垂直制表符。 - abuduba

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接