Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove new lines and returns from php string?

A php variable contains the following string:

<p>text</p> <p>text2</p> <ul> <li>item1</li> <li>item2</li> </ul> 

I want to remove all the new line characters in this string so the string will look like this:

<p>text</p><p>text2><ul><li>item1</li><li>item2</li></ul> 

I've tried the following without success:

str_replace('\n', '', $str); str_replace('\r', '', $str); str_replace('\r\n\', '', $str); 

Anyone knows how to fix this?

like image 278
Yens Avatar asked Oct 21 '10 10:10

Yens


People also ask

How remove all new lines from a string in PHP?

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

How do I remove all new lines from a string?

The strip() method will remove both trailing and leading newlines from the string. It also removes any whitespaces on both sides of a string.

Does PHP trim Remove newline?

Yes it does, see the manual: This function returns a string with whitespace stripped from the beginning and end of str .

How can I remove part of a string in PHP?

The substr() and strpos() function is used to remove portion of string after certain character. strpos() function: This function is used to find the first occurrence position of a string inside another string. Function returns an integer value of position of first occurrence of string.


1 Answers

You need to place the \n in double quotes.
Inside single quotes it is treated as 2 characters '\' followed by 'n'

You need:

$str = str_replace("\n", '', $str); 

A better alternative is to use PHP_EOL as:

$str = str_replace(PHP_EOL, '', $str); 
like image 159
codaddict Avatar answered Sep 28 '22 05:09

codaddict