tags:

views:

90

answers:

4

is there any php method to remove new line char from string?

$str ="
Hi
there
";

my string contains a new line char between 'Hi' and 'there' i want output as a "Hi there".I don't want to use regular expression.

+2  A: 

$str=str_replace("\n", "", $str); should do it.

"\n" represents a newline in php.

no
I second this answer.
David
misses out \r line termination
nathan
nathan, see my comment on Alex's answer.
no
+6  A: 

This is a bit confusing

is there any php method to remove new line char from string?

It looks like you actually want them replaced with a space.

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

Assuming the replacing goes from left to right, this should suit Windows text files.

The first grouping is to match Windows newlines which use both \r and \n.

alex
now produces ' Hi there ', if line terminator was both \r and \n as in windows files then you get double spacing
nathan
just needs the double space handler now - almost there (ps will +1 in oo 6 minutes, ty for the limits so)
nathan
@nathan What are you saying will double space - shouldn't the first replace cover the combination with a single space, and then the others will remove the Unix style line endings?
alex
No reason to use `array("\r\n", "\n", "\r")` ... `array("\n", "\r")` should do it. But then again, if the input's coming from a web browser, "\n" should be enough I think...
no
@alex )
nathan
+1  A: 

To get the expected results, you'll be needing:

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

or with regex (which is fail safe, you can't account for all the additional spacing you may get with str_replace version):

$str = trim(preg_replace( array('/\v/','/\s\s+/'), ' ' , $str)); // 'Hi there'
nathan
The OP said they don't want to use a regular expression.
alex
lol noted and sorted!
nathan
A: 

Hello,

You can use below script.

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

Thanks

Yunus Malek