A common problem many first time developers come across is preserving line breaks in a textarea after a form is submitted. This article will show you how to fix this problem in PHP and JavaScript. The code can also be easily converted to any other server side language you maybe using.
In PHP simply use built in nl2br function
$textAreaText = "This is a test\nThis is a test\nThis is a test"; echo $textAreaText; echo "<br /><br />"; echo nl2br($testAreaText);
The above example will output:
This is a testThis is a testThis is a test This is a test This is a test This is a test
As you can see using the nl2br() function converted all \n characters to <br/>, which the browser knows how to render. Visit the nl2br php.net manual page for more information.
JavaScript has no built in function however the good folks over at PHP.JS have converted a bunch of PHP functions to their JavaScript equivalents.
function nl2br (str, is_xhtml) {
var breakTag = '<br />';
if (typeof is_xhtml != 'undefined' && !is_xhtml) {
breakTag = '<br>';
}
return (str + '').replace(/([^>]?)\n/g, '$1'+ breakTag +'\n');
}
You can easily convert the function to any other language that you may use for server side scripting by using that particular languages' built-in string replace function.