How to Preserve Line Breaks in <textarea> after a Form is Submitted

Published by Utkarsh Patel on 06/05/09 14:28:34
Last edited on 06/05/09 16:33:16

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.

About the Author

Utkarsh Patel is one of our newest members, and he could not have come at a better time. He has helped bring back stability and control to Techlicity Ventures during our rapid growth. If he isn't marvelling at a recently discovered Oracle feature or technique he is bothering the rest of the team on why we should move everything over to Oracle databases. Utkarsh complements the team well with his determination and sound research.

Bookmark and Share
Blog Widget by LinkWithin
blog comments powered by Disqus

Valid XHTML 1.0!