[php] How to remove line breaks (no characters!) from the string?

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.

This question is related to php html replace line-breaks nl2br

The answer is


str_replace(PHP_EOL, null, $str);


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.


$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

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(array("\r\n", "\r", "\n"), "<br />", $string);

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

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.


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

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

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


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

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

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


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.

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to replace

How do I find and replace all occurrences (in all files) in Visual Studio Code? How to find and replace with regex in excel How to replace text in a column of a Pandas dataframe? How to replace negative numbers in Pandas Data Frame by zero Replacing few values in a pandas dataframe column with another value How to replace multiple patterns at once with sed? Using tr to replace newline with space replace special characters in a string python Replace None with NaN in pandas dataframe Batch script to find and replace a string in text file within a minute for files up to 12 MB

Examples related to line-breaks

HTML5 tag for horizontal line break Split string in JavaScript and detect line break Match linebreaks - \n or \r\n? How to linebreak an svg text within javascript? What is the difference between a "line feed" and a "carriage return"? Bash: Strip trailing linebreak from output How to read a file without newlines? How to break lines in PowerShell? How do I specify new lines on Python, when writing on files? How to remove line breaks (no characters!) from the string?

Examples related to nl2br

How do I hide the PHP explode delimiter from submitted form results? How to remove line breaks (no characters!) from the string? line breaks in a textarea How can I replace newline or \r\n with <br/>?