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
The line break can be removed from string by using str_replace() function.
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.
You need: $str = str_replace("\n", '', $str); A better alternative is to use PHP_EOL as: $str = str_replace(PHP_EOL, '', $str);
Using new line tags: Newline characters \n or \r\n can be used to create a new line inside the source code.
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With