197

This might appear to be a dupe, but rest assured it isn't - I have searched both SO as well as the rest of the web for an answer to my problem and ended up finding the same insufficient "solutions" over and over. Anyhow, here it goes:

I'm saving user input from a textarea to a MySQL database (within a WordPress environment, but that ought not to matter to this problem, I believe). It is later retrieved from the DB to be shown to Admins in the backend of the site. The problem occurs when users submit text with line breaks (i.e. hit the Enter key).

A sample string might look like this:

Dear friends, I just wanted so Hello. How are you guys? I'm fine, thanks!

Greetings,
Bill

There are no end of line characters ("\n", "\r", or the like) in the string.

I am using nl2br() on it to generate HTML output, but that's not enough. The result then is:

Dear friends, I just wanted so Hello. How are you guys? I'm fine, thanks!<br />
<br />
Greetings,<br />
Bill

Which, as far as I understand it, is the expected nl2br() result, as that inserts the tags and isn't supposed to replace the line-breaks in the first place?

However the format I need would be this:

Dear friends, I just wanted so Hello. How are you guys? I'm fine, thanks!<br /><br />Greetings,<br />Bill

If the string had EOL characters such as "\n" in it, I'd hit it with either str_replace() or preg_replace() and be done with it, but I have no clue what needle to feed either of those functions if there ain't no characters there in the first place.

I can manually access the relevant field in the DB, hit Backspace for every linebreak and what I later on want to do with the string works. So I know I need the above format.

Ben Roux
  • 7,308
  • 1
  • 18
  • 21
Johannes Pille
  • 4,073
  • 4
  • 26
  • 27
  • If the string looks like your first example, then how can you say it has no line break characters in it? It's got at least two: two in a row after "thanks!" – Ernest Friedman-Hill May 25 '12 at 15:59
  • Fair enuff @ErnestFriedman-Hill, you're obviously right - there's "something" there, it's just neither visible not anything I know. – Johannes Pille May 25 '12 at 16:03
  • I also can't see how is it possible to have new lines without line break characters. Can you use an hex editor to inspect the string - I am sure you will find the characters for new lines... – nettle May 25 '12 at 16:03

13 Answers13

585

Ben's solution is acceptable, but str_replace() is by far faster than preg_replace()

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

Using less CPU power, reduces the world carbon dioxide emissions.

Community
  • 1
  • 1
Demis Palma ツ
  • 7,669
  • 1
  • 23
  • 28
  • 7
    Can't believe this answer doesn't get more cred. 100 thumbs up to this over preg_replace() – pim Feb 21 '14 at 20:07
  • 82
    IMPORTANT: Use DOUBLE QUOTES around the carriage-return and newline codes. These won't get processed correctly if you use single quotes! – bwright May 05 '14 at 18:55
  • This. @bwright This is why I failed to come up with a working solution myself back in the day. I *did* try str_replace with both carriage returns and line feeds - but using single quotes. Was unaware of the difference two years back. Sometimes solutions are not that complicated after all... – Johannes Pille Sep 11 '14 at 06:41
  • 69
    Thumbs up -> "Using less CPU power, reduces the world carbon dioxide emissions." – Jan May 20 '15 at 14:27
  • 3
    @Joeri: That last one will never get called since it would be handled by the first two. It's redundant code. – nightfox89 Nov 02 '15 at 15:02
  • 1
    $buffer = str_replace(["\r\n","\r","\n"], "", $buffer); Some OS's like \r\n – Joeri Nov 03 '15 at 20:12
  • 5
    @Joeri Considering str_replace removes *all* occurrences, wouldn't \r and \n both ALL be removed anyway? – Bram Vanroy Apr 18 '16 at 13:17
  • If you just want to remove the line breaks, don't forget to replace with ' ', so that would be: `$text =str_replace(array("\r", "\n"), ' ', $text);` – sneaky Mar 14 '19 at 15:16
  • OMG, you can use an array as search parameter for str_replace! – roelleor May 05 '20 at 10:37
  • "...reduces the world carbon dioxide emissions" may have been said in humour, but if you think about it, only you can prevent forest fires. – Parapluie Oct 08 '20 at 15:20
  • This functions betters than the one in Ben's answer. – Tom Feb 07 '21 at 08:08
  • Upvoted for talking about the environment ! – MacTavish Jul 07 '23 at 23:07
436

You should be able to replace it with a preg that removes all newlines and carriage returns. The code is:

preg_replace( "/\r|\n/", "", $yourString );

Even though the \n characters are not appearing, if you are getting carriage returns there is an invisible character there. The preg replace should grab and fix those.

Charles
  • 4,372
  • 9
  • 41
  • 80
Ben Roux
  • 7,308
  • 1
  • 18
  • 21
  • Unbelievable. I could have sworn to have tried everything along the lines of yours and @bsdnoobz answers, which both do the job. Oh well, whatever mental block I had there, both of you saved me tons of time. Turned out to be quite a daft question, I guess. Thanks guys! – Johannes Pille May 25 '12 at 16:12
  • 7
    Note that this won't match all line breaks, i.e. those created on Windows systems. To catch these, you can use the following RegEx instead `/\r|\n|\r\n/` – Toastrackenigma Feb 17 '18 at 07:23
  • 7
    use \R (which represents any line ending sequence) https://stackoverflow.com/a/16274784/1491212 – Armel Larcier May 17 '18 at 12:20
19
$str = "
Dear friends, I just wanted so Hello. How are you guys? I'm fine, thanks!<br />
<br />
Greetings,<br />
Bill";

echo str_replace(array("\n", "\r"), '', $str);  // echo $str in a single line
flowfree
  • 16,356
  • 12
  • 52
  • 76
15

It's because nl2br() doesn't remove new lines at all.

Returns string with <br /> or <br> inserted before all newlines (\r\n, \n\r, \n and \r).

Use str_replace instead:

$string = str_replace(["\r\n", "\r", "\n"], "<br />", $string);
Phil
  • 422
  • 1
  • 5
  • 20
kenorb
  • 155,785
  • 88
  • 678
  • 743
12

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

function strip_carriage_returns($string)
{
    return str_replace(["\n\r", "\n", "\r"], '', $string);
}

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

Phil
  • 422
  • 1
  • 5
  • 20
tfont
  • 10,891
  • 7
  • 56
  • 52
10

To work properly also on Windows I'd suggest to use

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

"\r\n" - for Windows, "\r" - for Mac and "\n" - for Linux

Phil
  • 422
  • 1
  • 5
  • 20
Ajjaah
  • 141
  • 1
  • 5
  • 3
    Sorry mate, but even having been the one asking back in '12, I can tell you with absolute certainty that this is redundant. Ask yourself the following: If all `\r` and `\n` are removed in the string, why would that not be the case for those that follow each other directly? – Johannes Pille Sep 11 '14 at 06:42
  • Really, this obvious thing haven't came to my mind... Thanks :) I just realized that I have had troubles with it, but it was other way round, I used `\r\n` on Windows and it didn't work on Linux. – Ajjaah Sep 12 '14 at 12:14
  • Well, I am using this function to replace line breaks with commas so an address is a single line text, so replacing `\r\n` FIRST would help, as that means one comma rather than two for each part if that line break – Martin Jan 15 '15 at 11:12
  • @Martin Yes, you are right, I just realized the same, so we replace `\r\n` first, then we replace `\r` and `\n`, I've edited my answer. – Ajjaah Feb 20 '15 at 09:32
  • 2
    This is still redundant, if you going to remove all the `\r` and `\r`, there is no need to remove `\r\n`, you can user `str_replace(array("\r","\n"), "", $buffer);` to get the same result. – stramin Feb 15 '19 at 13:14
10

str_replace(PHP_EOL, null, $str);

Rafanake
  • 159
  • 1
  • 7
  • 1
    while this may answer the question.It is advised to explain a little about your answer. – Anirudh Sharma Jul 06 '15 at 13:53
  • 1
    PHP_EOL doesn't always work when you read string. It does when you write them. – nightfox89 Nov 02 '15 at 15:03
  • 1
    Code-only answers are low value on StackOverflow because they do very little to educate the OP and future readers. – mickmackusa May 11 '18 at 10:10
  • 3
    **WARNING:** This is an unreliable answer. `PHP_EOL` is defined differently on different systems. Sometimes it is a line feed, and other times it is a carriage return followed by a line feed. As a result, **this will fail** in some circumstances, potentially creating an attack vector (for example, when creating email headers). `PHP_EOL` should only be used to *output* information and not decipher *input*. **DO NOT USE** – pbarney Jun 25 '21 at 14:00
8

You can also use PHP trim

This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:

  • " " (ASCII 32 (0x20)), an ordinary space.
  • "\t" (ASCII 9 (0x09)), a tab.
  • "\n" (ASCII 10 (0x0A)), a new line (line feed).
  • "\r" (ASCII 13 (0x0D)), a carriage return.
  • "\0" (ASCII 0 (0x00)), the NUL-byte.
  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.
Gijs de Jong
  • 967
  • 9
  • 14
  • 7
    This will only target newlines at the start and end of the string. Newlines in the middle of the string will be untouched. – mickmackusa May 11 '18 at 10:12
2

I think my answer is too late but I got same extra line issue while using it in JS script, but it works like this

This will add <br /> and line breaks in string.

$text = nl2br($text);

This line will remove extra line.

$text = preg_replace("/\r|\n/", "", $text);

Replacing <br /> with any unwanted common symbol like this asterisk ** while inserting in DB:

$text = str_replace("<br />","**",$text );

And when I want to use it in program that time I use it replacing **.

$text = str_replace("**","\\n",$text );

Then use $text in program

Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
Shubham Dange
  • 173
  • 13
1

I use 3 lines to do this job, so consider $s as your "stuff"...

$s=str_replace(chr(10),'',$s);
$s=str_replace(chr(13),'',$s);
$s=str_replace("\r\n"),'',$s);
  • Legend:

chr(10)___a line feed

chr(13)___the return

\r\n______a new line

PYK
  • 3,674
  • 29
  • 17
0

Alternative built-in: trim()

trim — Strip whitespace (or other characters) from the beginning and end of a string
Description ¶
trim ( string $str [, string $character_mask = " \t\n\r\0\x0B" ] ) : string

This function returns a string with whitespace stripped from the beginning and end of str.
Without the second parameter, trim() will strip these characters:

    " " (ASCII 32 (0x20)), an ordinary space.
    "\t" (ASCII 9 (0x09)), a tab.
    "\n" (ASCII 10 (0x0A)), a new line (line feed).
    "\r" (ASCII 13 (0x0D)), a carriage return.
    "\0" (ASCII 0 (0x00)), the NUL-byte.
    "\x0B" (ASCII 11 (0x0B)), a vertical tab.

It's there to remove line breaks from different kinds of text files, but does not handle html.

NVRM
  • 11,480
  • 1
  • 88
  • 87
0

after trying literally all of these solutions.. the only thing that worked was to (urlencode - then replace - then urldecode)

$jsonDump = urlencode($jsonDump);
$jsonDump = str_replace("%5Cr","",$jsonDump);
$jsonDump = str_replace("%5Cn","",$jsonDump);
$jsonDump = urldecode($jsonDump);
TedCampos
  • 17
  • 2
-1

You can use preg_replace in order to replace parts of a string matching a regular expression, like:

preg_replace("/\s+/","",$string);
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Chirag
  • 97
  • 1
  • 3