Converting textarea newlines to linebreaks in PHP

The text area element in HTML does not automatically convert newlines to line breaks, so a simple little function needs to be created to do so. There is the built-in PHP function nl2br but if does not work effectively when your user enters multiple blank lines. Here is a little PHP function to help with that: (I found this in the PHP docs)

1
2
3
4
5
6
7
8
9
10
11
12
/**
 * Converts a string with C-style newlines to HTML line breaks
 * @param String $string The dirty string
 * @param Integer $num Maximum number of repeating newlines
 * @return String Converted String
*/
function nl2br_limit($string, $num = 2)
{
    $dirty = preg_replace('/\r/', '', $string);
    $clean = preg_replace('/\n{4,}/', str_repeat('', $num), preg_replace('/\r/', '', $dirty));
    return nl2br($clean);
}

Of course, you might want to convert this back to display in a text box again. You can use this little function to do so:

1
2
3
4
5
6
7
8
9
10
11
/**
 * Converts a string with HTML linebreaks to C-style newlines
 * @param String $string
 * @return String Converted String
*/
function br2nl_limit($string)
{
    $string = str_ireplace('<br />', "\n", $string);
    $string = str_ireplace('<br>', "\n", $string);
    return $string;
}

If you find that there are spaces at each line break, just add a space after the br in the str_ireplace, like so str_ireplace(‘
‘, “\n”, $string);

Posted on in PHP