开发者

How to escape new line from string

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.


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.


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

"\n" represents a newline in php.


There is no way to escape newline in PHP.

As mentioned in PHP documentation on strings after listing all escaped characters:

As in single quoted strings, escaping any other character will result in the backslash being printed too.

So you can do it by breaking your string in each line and concatenating them by dot like this:

$str = "Hi " .
"there" .
"!";


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'


You can use below script.

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

Thanks

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜