views:

69

answers:

5

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?

+5  A: 

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);
codaddict
-1 PHP_EOL has nothing to do here
Col. Shrapnel
@Col: Why not ?
codaddict
because it's about system where PHP runs, not about system where the text come from. Isn't it obvious?
Col. Shrapnel
+1  A: 

You have to wrap \n or \r in "" not ''.

bazmegakapa
A: 

This should be like

str_replace("\n", '', $str);
str_replace("\r", '', $str);
str_replace("\r\n\", '', $str);
Asif Mulla
A: 

here you go $string = str_replace(PHP_EOL,null,$string) PHP_EOL is the cross platform Declaration for EndOfLine

Hannes
`PHP_EOL` is not crossplatform, but the opposite. It's the EndOfLine for the very platform PHP is running on. Downvote wasnt me though.
Gordon
@Gordon, you are right correct would be "a Cross Plattform Solution that includes all possible Linebreaks [...] " ... well, wrong wording right solution, anyhow, downvote was probably from Col. Shrapnel
Hannes
@Hannes no, no. That's exactly what it's not. It does not include all possible line breaks. It's a constant that will contain the appropriate linebreak for the current platform only. If you open a file created on a Linux machine and try to replace the newlines with PHP_EOL from PHP on a Windows machine, it will not work.
Gordon
who said it's right solution? what do you mean "all possible Linebreaks"? in what form? an array or what?
Col. Shrapnel
A: 

And how would you replace all newlines ONLY within an unordered list

<ul>//replace all new line charcaters within this tags</ul>

so that only this would happen:

<p>text</p>
<p>text2</p>
<ul><li>item1</li><li>item2</li></ul>
yens resmann
You should use a DOM Parser for that. See [Best Methods to Parse HTML](http://stackoverflow.com/questions/3577641/best-methods-to-parse-html/3577662#3577662).
Gordon