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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9926277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:55:57  来源:igfitidea点击:

remove new line characters from txt file using php

phpnewlinetext-files

提问by Mira

I have txt file its content like this

我有 txt 文件,它的内容是这样的

Hello  
World   
John  
play  
football  

I want to delete the new line character when reading this text file, but I don't know how it look like the file .txt and its encoding is utf-8

我想在读取这个文本文件的时候删除换行符,但是我不知道它看起来像文件 .txt 并且它的编码是 utf-8

回答by abuduba

Just use filefunction with FILE_IGNORE_NEW_LINESflag.

只需使用file带有FILE_IGNORE_NEW_LINES标志的函数。

The filereads a whole file and returns an array contains all of the file lines.

file读取整个文件并返回一个数组包含的所有文件中的行。

Each line contains new line character at their end as default, but we can enforce trimming by FILE_IGNORE_NEW_LINESflag.

默认情况下,每一行的末尾都包含换行符,但我们可以通过FILE_IGNORE_NEW_LINES标志强制修剪。

So it will be simply:

所以它会很简单:

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

The result should be:

结果应该是:

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"
}

回答by Alex Turpin

There are different kind of newlines. This will remove all 3 kinds in $string:

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

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

回答by r-sal

If your going to be putting the lines into an array, an assuming a reasonable file size you could try something like this.

如果您要将行放入数组中,假设文件大小合理,您可以尝试这样的操作。

$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  
)

*/

回答by ghoti

I note that the way it was pasted in the question, this text file appears to have space characters at the end of each line. I'll assume that was accidental.

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

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