remove new line characters from txt file using php

2019-01-15 09:33发布

I have txt file its content like this

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

4条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-15 10:18

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

$string = str_replace(array("\r", "\n"), '', $string)
查看更多
三岁会撩人
3楼-- · 2019-01-15 10:28

Just use file function with FILE_IGNORE_NEW_LINES flag.

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

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

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"
}
查看更多
甜甜的少女心
4楼-- · 2019-01-15 10:28

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  
)

*/
查看更多
【Aperson】
5楼-- · 2019-01-15 10:31

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";
查看更多
登录 后发表回答