how to remove new lines and returns from php strin

2019-01-31 17:24发布

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?

8条回答
倾城 Initia
2楼-- · 2019-01-31 17:59

You have to wrap \n or \r in "", not ''. When using single quotes escape sequences will not be interpreted (except \' and \\).

The manual states:

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

  • \n linefeed (LF or 0x0A (10) in ASCII)

  • \r carriage return (CR or 0x0D (13) in ASCII)\

  • (...)

查看更多
smile是对你的礼貌
3楼-- · 2019-01-31 18:00
$no_newlines = str_replace("\r", '', str_replace("\n", '', $str_with_newlines));
查看更多
Ridiculous、
4楼-- · 2019-01-31 18:11

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);
查看更多
我只想做你的唯一
5楼-- · 2019-01-31 18:12

To remove new lines from string, follow the below code

$newstring = preg_replace("/[\n\r]/","",$subject); 
查看更多
Summer. ? 凉城
6楼-- · 2019-01-31 18:15

Something a bit more functional (easy to use anywhere):

function replace_carriage_return($replace, $string)
{
    return str_replace(array("\n\r", "\n", "\r"), $replace, $string);
}

Using PHP_EOL as the search replacement parameter is also a good idea! Kudos.

查看更多
该账号已被封号
7楼-- · 2019-01-31 18:15

Correct output:

'{"data":[{"id":"1","reason":"hello\\nworld"},{"id":"2","reason":"it\\nworks"}]}'

function json_entities( $data = null )
{           
    //stripslashes
    return str_replace( '\n',"\\"."\\n",
        htmlentities(
            utf8_encode( json_encode( $data)  ) , 
            ENT_QUOTES | ENT_IGNORE, 'UTF-8' 
        )
    );
}
查看更多
登录 后发表回答