Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove new line characters from txt file using php

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

like image 291
Mira Avatar asked Mar 29 '12 13:03

Mira


People also ask

How to remove new line characters from a string PHP?

The line break can be removed from string by using str_replace() function.

How do I get rid of the new line character in a text file?

In the file menu, click Search and then Replace. In the Replace box, in the Find what section, type ^\r\n (five characters: caret, backslash 'r', and backslash 'n'). Leave the Replace with section blank unless you want to replace a blank line with other text.

How to remove r n in PHP?

You need: $str = str_replace("\n", '', $str); A better alternative is to use PHP_EOL as: $str = str_replace(PHP_EOL, '', $str);

How do I add a new line to a string in PHP?

Using new line tags: Newline characters \n or \r\n can be used to create a new line inside the source code.


1 Answers

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"
}
like image 74
abuduba Avatar answered Sep 27 '22 19:09

abuduba