47

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?

kapa
  • 77,694
  • 21
  • 158
  • 175
Yens
  • 915
  • 4
  • 12
  • 24
  • You might find [`s($str)->normalizeLineEndings('')`](https://github.com/delight-im/PHP-Str/blob/8fd0c608d5496d43adaa899642c1cce047e076dc/src/Str.php#L540) helpful, as found in [this standalone library](https://github.com/delight-im/PHP-Str). It removes all types of newlines, including Unicode chars. – caw Jul 27 '16 at 00:53
  • 1
    Just use `"` instead of `'`. – Nabi K.A.Z. Jun 17 '19 at 18:23

10 Answers10

110

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
  • 445,704
  • 82
  • 492
  • 529
  • 4
    PHP_EOL indeed doesn't work. PHP won't find them correctly in str_replace. I have to do this for correct html display: replace \r\n with
    (this is for CRLF under Windows), then replace \n with
    (this is for LF under Linux), lastly, replace \r with empty string (this shouldn't mean anything)
    – Scott Chu Jul 09 '15 at 09:39
  • Yes to double quotes. No to PHP_EOL as explained above. – Paolo Feb 01 '17 at 07:19
  • 8
    Indeed, `PHP_EOL` does not work. Should be `["\r\n", "\r", "\n"]` instead. – Matt K Feb 01 '17 at 22:14
  • I wasted lot of time trying to debug my code because of this issue. Thanks! – Bhargav Nanekalva Feb 23 '17 at 10:05
  • 2
    Do you really need the `"\r\n"` in `["\r\n", "\r", "\n"]`? It's already going to globally remove `\r` and \n` everywhere, right? – James M. Lay Dec 10 '17 at 00:28
  • 1
    FWIW, in PHP 7 I was able to use `$str = str_replace(PHP_EOL, '', $str);` and it successfully worked. – JustCarty Dec 11 '17 at 11:12
  • 4
    @JustCarty That might have worked in your specific case, but it assumes that the value of `$str` was created on the same platform as the system running the script. If you mix windows and unix, you'll have a bad day. – musicin3d Mar 16 '18 at 21:59
  • @musicin3d I know this is old, but I guess I just want to know why everyone is trashing his answer for using a php constant when the only reference we have is A php environment. I get that "\r\n" will cover more cases, but you're all on your high horse without considering "\025" for IBM... I still think PHP_EOL is the best answer in this context because the supposed need for "\r\n" is based on an assumption. I'm guessing that's why codaddict has ~100x or more the reputation of everyone else in these comments. But I'm a noob myself... maybe he's changed his mind after 8 years? Hope he weighs in – TCooper Oct 16 '18 at 22:49
  • @TCooper As with all things, it really depends on what assumptions you can actually make. Where will the app run, and where will the input (eg. file, database, etc) come from? If it will only ever run on one architecture and you know which one, you could get away with using the native return character. If the app will run on one arch and the same arch created/creates the input, you should use PHP_EOL. If, however, you can't guarantee where it will be run or which arch created the input you'd better be prepared to handle return characters not natively supported on all possible architectures. – musicin3d Oct 17 '18 at 23:00
  • @TCooper For example, what if you use linux, your teammate uses mac, and your tester uses windows? What happens when you copy one person's database to another? What happens if you move your app which was written in a "cross-platform" language to another platform? – musicin3d Oct 17 '18 at 23:04
21

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

  • (...)

Community
  • 1
  • 1
kapa
  • 77,694
  • 21
  • 158
  • 175
  • 1
    This is important. I used to use single quote `'` and the text always be replaced with `"\n"`(type of string). If you're confusing with this, keep that in mind.... – Benyi May 04 '17 at 17:53
13

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.

tfont
  • 10,891
  • 7
  • 56
  • 52
  • 1
    Borrowed for http://stackoverflow.com/questions/33850820/parse-txt-files-and-turn-them-into-static-html-files/33851340#33851340 Thanks! +1 – Steve Nov 22 '15 at 16:04
7

To remove new lines from string, follow the below code

$newstring = preg_replace("/[\n\r]/","",$subject); 
saravanavelu
  • 494
  • 6
  • 13
6

This should be like

str_replace("\n", '', $str);
str_replace("\r", '', $str);
str_replace("\r\n", '', $str);
JRulle
  • 7,448
  • 6
  • 39
  • 61
Asif Mulla
  • 1,652
  • 2
  • 22
  • 32
3

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);
rvandoni
  • 3,297
  • 4
  • 32
  • 46
2

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' 
        )
    );
}
Jonathan
  • 41
  • 7
  • This isn't even remotely an answer to this question. In fact, the **only** thing that the question and the answer have in common is the newline character '\n' literal and the use of `str_replace`, although for entirely different purposes. – Michael Gaskill Jun 28 '16 at 01:50
  • You have reason, works for me because i use TextArea and sometimes need new line and this data send by angular ng-init – Jonathan Jul 07 '16 at 18:07
1
$no_newlines = str_replace("\r", '', str_replace("\n", '', $str_with_newlines));
Collin Anderson
  • 14,787
  • 6
  • 68
  • 57
0

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.

Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
0
$str = "Hello World!\n\n";
echo chop($str);

output : Hello World!
DILSHAD AHMAD
  • 215
  • 2
  • 4