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.