43

I have a post form, which inserts my text in a MySQL database.

I use

$post_text = mysql_real_escape_string(htmlspecialchars($_POST['text']));

and want to replace the \r\n which was automatically added.

I tried

$text = str_replace('\\r\\n','', $text);
$text = str_replace('\r\n','', $text);
$text = str_replace('\\R\\N','', $text);
$text = str_replace('\R\N','', $text);
$text = str_replace('/\r\\n','', $text);
$text = str_replace('/r/n','', $text);
$text = str_replace('/\R\\N','', $text);
$text = str_replace('/R/N','', $text);

but \r\n is always included in my database entries.

How can I fix this?

Shi
  • 4,178
  • 1
  • 26
  • 31
njaknjak
  • 755
  • 4
  • 9
  • 14
  • Why was `\r\n` "automatically added"? I'd look into fixing that anomaly, rather than trying (in vain) to hack around it after-the-fact. – Lightness Races in Orbit Mar 27 '11 at 14:12
  • possible duplicate of [How to remove line breaks (no characters!) from the string?](http://stackoverflow.com/questions/10757671/how-to-remove-line-breaks-no-characters-from-the-string) – kenorb Mar 03 '15 at 00:30

6 Answers6

84

The main problem you have with all the variations you've tried is that both \n and \r are escape characters that are only escaped when you use them in a double-quoted string.

In PHP, there is a big difference between '\r\n' and "\r\n". Note the single-quotes in the first, and double-quotes in the second.

So: '\r\n' will result in a four character string containing a slash, an 'r', another slash and an 'n', whereas "\r\n" will contain two characters, those being the new line and carriage return characters.

So the direct answer to your question is that you need to use the second of the examples you gave in the question, but with double quotes instead of single quotes:

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

It's worth pointing out that this will remove all new lines from the input, and replace them with nothing. If there is more than one new line in the input, they will all be removed. Without knowing more about your application, I don't know if this is what you want, but here are some thoughts:

  • If you only want to remove blank lines (and other white space) from the end of the input string, you can use the trim() function instead.

  • If you want to retain the formatting for output to HTML, then the nl2br() function will help you. If you want to output to HTML without the formatting, then you may not need to remove them, as the browser will not render line breaks from \n characters.

  • If you replace new lines with nothing, as per your example, the last word of the first line will now run directly into the first word of the second line, and so on. You may prefer to replace them with a space character rather than nothing.

  • It is possible that users may submit the input with only \n without the matching \r, or vice-versa (this may be due to their OS or browser, or a deliberate hack, or a number of other reasons). If you want to replace all instances of both these characters, a more reliable way to do it would be to replace them individually, rather than relying on them being next to one-another. str_replace() allows you to do this by specifying them in an array. You can also use strtr() or preg_replace() to achieve the same goal.

starball
  • 20,030
  • 7
  • 43
  • 238
Spudley
  • 166,037
  • 39
  • 233
  • 307
  • After trying different things this solution actually worked out. And i get the point that while using escape characters we need to use double quotes so that it is treated as a single character. – Sasi varna kumar Sep 11 '15 at 07:13
  • Also of note, I could not figure out why I could not replace it in my text. I did a database export and I found that it was saved with double slashes, so I added that to another replace line in php \\r\\n – carnini Apr 19 '21 at 12:50
  • 1
    @carnini - well done for finding that. You should consider digging into the code that creates the double-encoded slashes as well, because things like that indicate there may be bigger issues as well. It is better to fix the root problem than to write work-arounds for the broken data it causes. – Spudley Apr 21 '21 at 08:48
14

try also

$text = str_ireplace(array("\r","\n",'\r','\n'),'', $text);
Itay Moav -Malimovka
  • 52,579
  • 61
  • 190
  • 278
5
   if (!is_numeric($value)) {
        $value = mysql_real_escape_string(trim($value));
        $value = str_replace("\\r\\n",'', $value);
    }
Shi
  • 4,178
  • 1
  • 26
  • 31
V A S
  • 3,338
  • 4
  • 33
  • 39
2

I would suggest to use strtr() for multiple replacements when dealing with database entries. Also use double quotes as @Spudley suggested.

$text = strtr($text, array(
          "\r\n" => "",
          "\r" => "",
          "\n" => "",
          "\t" => " "));

strtr() -> Once a substring has been replaced, its new value will not be searched again.

http://php.net/strtr

str_replace() -> If search is an array and replace is a string, then this replacement string is used for every value of search. The converse would not make sense, though.

http://php.net/str_replace

fat_mike
  • 877
  • 12
  • 27
1

To preserve multiple line breaks I'm doing this:

$tempCONTENT = mysqli_real_escape_string($con, $_POST['promotion_content']);
$tempCONTENT = str_ireplace(array("\r\n","\r","\n",'\r','\n'),'<br />', $tempCONTENT);
$previewFORMATTED = str_ireplace(array('<br /><br />'),'<br />', $tempCONTENT);
echo $previewFORMATTED;

This is being used to process a text area form field. It preserves the number of line breaks the user inputs, changing them from \r\n to [br /]

I'm using this to display the input so the user can check it before I add it to the database. Using two submit buttons, one to check and another to submit, that doesn't do this. It just adds the data using mysqli_real_escape_string

I'm then using a str_ireplace to turn the correct number of [br /] back into \r\n so I can echo the result back into the text area to make it easy for them to edit.

So my final code looks like this:

$tempCONTENT = mysqli_real_escape_string($con, $_POST['promotion_content']);
$tempCONTENT = str_ireplace(array("\r\n","\r","\n",'\r','\n'),'<br />', $tempCONTENT);
$previewFORMATTED = str_ireplace(array('<br /><br />'),'<br />', $tempCONTENT);
echo $previewFORMATTED;
$formOUTPUT = str_ireplace(array('<br />'),"\r\n", $previewFORMATTED);

I've tested this on Safari and Chrome and it works fine. I've not tested IE, but nothing ever works on IE!

But I did find another issue. If the user enters HTML like this:

<h1>heading</h1><p>some text</p>

it's fine, but if they do the following (which is more likely)

<h1>heading</h1>
<p>some text</p>

Then I get a huge space between the heading and the paragraph.

I tried to fix it with this code:

$tempCONTENT = str_ireplace(array(">\r\n<",">\r<",">\n<",'>\r<','>\n<'),'><', $tempCONTENT);

but that didn't work :( I still get the huge gap as it's adding an extra [br /] between the h1 and p tags.

For now I'm just going to tell them to not add a line break between html tags and the result should be good :)

I hope somebody found this useful.

Steve Hall
  • 113
  • 1
  • 7
-3

For a MySQL database you shouldn't replace anything.

  • in case it's just literal \r\n in $post_text - it's okay, it's proper format for the SQL query.
  • in case it's \\r\\n in $post_text that becomes \r\n in the database - you have escaped your string twice and should not replace anything but rather get rid of excessive escaping

So, you have to make it look like \r\n in in the $post_text before insert, and you'll be able apply nl2br() function on it before output.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345