开发者

how to remove new lines and returns from php string?

开发者 https://www.devze.com 2023-01-20 23:17 出处:网络
A php variable contains the following string: <p>text</p> <p>text2</p> <ul>

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>item开发者_JAVA技巧1</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?


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);


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)\

  • (...)


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.


To remove new lines from string, follow the below code

$newstring = preg_replace("/[\n\r]/","",$subject); 


This should be like

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


you can pass an array of strings to str_replace, so you can do all in a single statement:

$content = str_replace(["\r\n", "\n", "\r"], "", $content);


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' 
        )
    );
}


$no_newlines = str_replace("\r", '', str_replace("\n", '', $str_with_newlines));


Replace a string :

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

u using also like, (%n, %t, All Special characters, numbers, char,. etc)

which means any thing u can replace in a string.


$str = "Hello World!\n\n";
echo chop($str);

output : Hello World!
0

精彩评论

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