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

使用php从txt文件中删除新行字符,php,newline,text-files,Php,Newline,Text Files,我有txt文件,它的内容是这样的 Hello World John play football 我想在阅读此文本文件时删除新行字符,但我不知道它是什么样子 txt文件及其编码为utf-8有不同类型的换行符。这将删除$string中的所有3种类型: $string = str_replace(array("\r", "\n"), '', $string) 我注意到问题中粘贴的方式,该文本文件似乎在每行末尾都有空格字符。我想那是偶然的 <?php // Ooen t

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

Hello  
World   
John  
play  
football  
我想在阅读此文本文件时删除新行字符,但我不知道它是什么样子
txt文件及其编码为utf-8

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

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

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

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

如果要将行放入数组,假设文件大小合理,可以尝试以下方法

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

*/

只需将
file
功能与
file\u IGNORE\u NEW\u行
标志一起使用即可

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

默认情况下,每行末尾都包含新行字符,但我们可以通过
FILE\u IGNORE\u new\u 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"
}

有2种还是3种?@Mira,3种(
\r
\n
,和
\r\n
),我的答案中的脚本处理了3种。Mira,你想用零替换还是用其他类型的空格替换?当任何单词超过40字节时,结果将无效(更不用说它只适用于每行单个单词)
trim
不是一个好选项,如果-将足以使用rtrim(您只需要修剪右侧)-不要忘记第二个参数,它是一个字符掩码。默认情况下,它将修剪:空格、制表符、新行、回车、空字节和垂直制表符。您也可以使用此参数:
$lines=file('file.txt',file_IGNORE_new_line | file_SKIP_EMPTY_line)
。这样您也可以跳过空新行!