search for in the  
<nl_langinfonumber_format>
Last updated: Thu, 19 May 2005

nl2br

(PHP 3, PHP 4, PHP 5)

nl2br --  Inserts HTML line breaks before all newlines in a string

Description

string nl2br ( string string )

Returns string with '<br />' inserted before all newlines.

Note: Starting with PHP 4.0.5, nl2br() is now XHTML compliant. All versions before 4.0.5 will return string with '<br>' inserted before newlines instead of '<br />'.

Example 1. using nl2br()

<?php
echo nl2br("foo isn't\n bar");
?>

this will output :

foo isn't<br />
 bar

See also htmlspecialchars(), htmlentities(), wordwrap(), and str_replace().



User Contributed Notes
nl2br
kristen at paristemi dot com
16-May-2005 03:12
A note to add to the br2nl. Since nl2br doesn't remove the line breaks when adding in the <br /> tags, it is necessary to strip those off before you convert all of the tags, otherwise you will get double spacing. Here is the modified function:

function br2nl($str) {
   $str = preg_replace("/(\r\n|\n|\r)/", "", $str);
   return preg_replace("=<br */?>=i", "\n", $str);
}
sebastian at no spam flashhilfe.de
10-May-2005 10:16
// Convert only <br> <br /> and <br    /> to newline

function br2nl($str) {
   return preg_replace('=<br */?>=i', "\n", $str);
}

The Script at the bottom whit '!<br.*>!iU' match tags like <break> or something.
jochem at vuilnisbak dot com
02-Apr-2005 10:43
For people trying br2nl, but getting stuck at double newlines (or at least more then needed), try this:

<?php
function br2nl($coffee) {
  
$coffee = str_replace("\r\n", "\n", $coffee); // make from windows-returns, *nix-returns
  
$coffee = str_replace("<br />\n", "\n", $coffee); // to retrieve it
  
return $coffee;
}
?>

The first thing \r\n is replacing linebreaks made on Windows systems. I believe *nix systems only place \n (not sure about it).

Have fun.

Jochem
webKami [at] akdomains.com
01-Apr-2005 06:54
here is the CSS friendly version, called nl2li_css()

Inputs a param css_class (default ="none") and pass it as class of All <li> List Items.

<?
function nl2li_css($str,$css_class = "none",$ordered = 0, $type = "1") {

//check if its ordered or unordered list, set tag accordingly
if ($ordered)
{
  
$tag="ol";
  
//specify the type
  
$tag_type="type=$type";
}
else
{   
  
$tag="ul";
  
//set $type as NULL
  
$tag_type=NULL;
}

// add ul / ol tag
// add tag type
// add first list item starting tag - use css class
// add last list item ending tag
$str = "<$tag $tag_type><li class=\"$css_class\">" . $str ."</li></$tag>";

//replace /n with adding two tags
// add previous list item ending tag
// add next list item starting tag - use css class
$str = str_replace("\n","</li><br />\n<li class=\"$css_class\">",$str);

//spit back the modified string
return $str;
}
?>

Suggestions welcome again :)
webkami [at] gmail dout com
30-Mar-2005 09:42
A handy function to convert new line \n seprated text into ordered or unordered list. I am calling it nl2li, suggestions welcome. Second optional parameter sets the list as ordered (1) or unordered (0 = default). Third parameter can be used to specify type of ordered list, valid inputs are "1" = default ,"a","A","i","I".

function nl2li($str,$ordered = 0, $type = "1") {

//check if its ordered or unordered list, set tag accordingly
if ($ordered)
{
   $tag="ol";
   //specify the type
   $tag_type="type=$type";
}
else
{   
   $tag="ul";
   //set $type as NULL
   $tag_type=NULL;
}

// add ul / ol tag
// add tag type
// add first list item starting tag
// add last list item ending tag
$str = "<$tag $tag_type><li>" . $str ."</li></$tag>";

//replace /n with adding two tags
// add previous list item ending tag
// add next list item starting tag
$str = str_replace("\n","</li><br />\n<li>",$str);

//spit back the modified string
return $str;
}
mike at openconcept dot ca
10-Mar-2005 12:02
There are other nl2p examples above, but think this one will provide nicer html.  Also threw in a very related br2p function for all of those folks who want to strip away the <br /> tags which give their designers the blues.

   /**
   * replacement for php's nl2br tag that produces more designer friendly html
   *
   * Modified from: http://www.php-editors.com/contest/1/51-read.html
   *
   * @param string $text
   * @param string $cssClass
   * @return string
   */
   function nl2p($text, $cssClass=''){

     // Return if there are no line breaks.
     if (!strstr($text, "\n")) {
         return $text;
     }

     // Add Optional css class
     if (!empty($cssClass)) {
         $cssClass = ' class="' . $cssClass . '" ';
     }

     // put all text into <p> tags
     $text = '<p' . $cssClass . '>' . $text . '</p>';

     // replace all newline characters with paragraph
     // ending and starting tags
     $text = str_replace("\n", "</p>\n<p" . $cssClass . '>', $text);

     // remove empty paragraph tags & any cariage return characters
     $text = str_replace(array('<p' . $cssClass . '></p>', '<p></p>', "\r"), '', $text);

     return $text;

   } // end nl2p

  /**
   * expanding on the nl2p tag above to convert user contributed
   * <br />'s to <p>'s so it displays more nicely.
   *
   * @param string $text
   * @param string $cssClass
   * @return string
   */
   function br2p($text, $cssClass=''){

     if (!eregi('<br', $text)) {
         return $text;
     }

     if (!empty($cssClass)) {
         $cssClass = ' class="' . $cssClass . '" ';
     }

     // put all text into <p> tags
     $text = '<p' . $cssClass . '>' . $text . '</p>';

     // replace all break tags with paragraph
     // ending and starting tags
     $text = str_replace(array('<br>', '<br />', '<BR>', '<BR />'), "</p>\n<p" . $cssClass . '>', $text);

     // remove empty paragraph tags
     $text = str_replace(array('<p' . $cssClass . '></p>', '<p></p>', "<p>\n</p>"), '', $text);

     return $text;
}

This is all code from Back-End CMS (http://www.back-end.org), a template based gpl php/mysql cms.

Mike
freedman AT freeformit . com
03-Mar-2005 06:45
here's a modified version that allows the addition of style tags to the <p> marker

function nl2p($str,$addtag='') {
   return str_replace('<p'.$addtag.'></p>', '', '<p'.$addtag.'>' . preg_replace('#\n|\r#', '</p>$0<p'.$addtag.'>', $str) . '</p>');
}

$x = "abc\ndef"
echo nl2p($x);  // outputs <p>abc</p>\n<p>def</p>

echo nl2p($x,' style="text-align:justify"');
// outputs <p style="text-align:justify">abc</p>\n<p style="text-align:justify">def</p>
asentis at gmail dot com
23-Feb-2005 07:06
If you want to respect W3C, you can use this function :

<?php
function nl2p($str)
{
  return
str_replace('<p></p>', '', '<p>' . preg_replace('#\n|\r#', '</p>$0<p>', $str) . '</p>');
}
?>

Cya :)
CGameProgrammer at gmail dot com
30-Jan-2005 07:28
It's important to remember that this function does NOT replace newlines with <br> tags. Rather, it inserts a <br> tag before each newline, but it still preserves the newlines themselves! This caused problems for me regarding a function I was writing -- I forgot the newlines were still being preserved.

If you don't want newlines, do:

$Result = str_replace( "\n", '<br />', $Text );
17-Jan-2005 02:04
string nl2br_indent ( string string [, mixed indent] )

This function adds break tags before newlines as nl2br and also indents the text.
If indent is not specified, string will not be indented.

<?php

function nl2br_indent($string, $indent = 0)
{
  
//remove carriage returns
  
$string = str_replace("\r", '', $string);

  
//convert indent to whitespaces if it is a integer.
  
if (is_int($indent)) {
      
//set indent to length of the string
      
$indent = str_repeat(' ', (int)$indent);
   }

  
//replace newlines with "<br />\n$indent"
  
$string = str_replace("\n", "<br />\n".$indent, $string);
  
//add  the indent to the first line too
  
$string = $indent.$string;

   return
$string;
}

?>

This is for example useful to indent text in html tags:

<?php

$str
= 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
In massa nunc, cursus eu, tincidunt in, eleifend non, enim. In ut felis. Nunc
scelerisque ante vel risus. Nulla quis metus non elit scelerisque tincidunt.'

echo '<html>'."\n";
echo
'  <p>'."\n";
echo
nl2br_indent($str, 4)."\n";
echo
'  </p>'."\n";
echo
'</html>'."\n";

?>

will return:

<html>
  <p>
   Lorem ipsum dolor sit amet, consectetuer adipiscing elit.<br />
   In massa nunc, cursus eu, tincidunt in, eleifend non, enim. In ut felis. Nunc<br />
   scelerisque ante vel risus. Nulla quis metus non elit scelerisque tincidunt.
  </p>
</html>

- $str is indented by 4 spaces.
spertica at tiscalinet dot it
14-Jan-2005 03:23
An easy way to get HTML formatted with <br> from a ASCII text file with CR & LF:

<?php
     $string_text
=file_get_contents("/path_to/file.txt"); // load text file in var
    
$new_text=nl2br($string_text); // convert CR & LF in <br> in newvar
    
echo $new_text; // print out HTML formatted text
    
unset($string_text, $new_text); // clear all vars to unload memory
 
?>
php at keithtyler dot com
05-Nov-2004 12:58
Take extreme care with nl2br(). It is a simple replacement function -- apparently equivalent to preg_replace("\n","<br \>\n").

It should not be used on input from HTML textareas, unless all HTML tags are stripped from the input first. nl2br() does not do anything special to newlines that occur within HTML elements (such as the <a> anchor tag).

Some browsers will submit textarea data with newlines inserted at the points where the user's input wrapped to the next line. This can cause anchor links to break and other erratic appearance of HTML:

<a <br \>href=http://us2.php.net/manual/en/function.nl2br.php>PHP nl2br()</a>

or worse:

<a href="http://www.site.com/user/page with <br />spaces.html">URL with spaces</a>

A lot of people use nl2br() to allow their users to insert explicit line and paragraph breaks via newlines, and their applications will exhibit this problem when used with such browsers.
php at sharpdreams dot com
05-Apr-2004 11:52
Better br2nl function (allows for non-valid XHTML tags). I find it useful for parsing 3rd party websites to convert their screwy BR formats to \n.

<?php
function br2nl( $data ) {
   return
preg_replace( '!<br.*>!iU', "\n", $data );
}
?>
greywyvern - greywyvern - com
05-Feb-2004 03:11
Just a couple adjustments to the function below.

<?php

function nl2br_pre($string, $wrap = 40) {
 
$string = nl2br($string);

 
preg_match_all("/<pre[^>]*?>(.|\n)*?<\/pre>/", $string, $pre1);

  for (
$x = 0; $x < count($pre1[0]); $x++) {
  
$pre2[$x] = preg_replace("/\s*<br[^>]*?>\s*/", "", $pre1[0][$x]);
  
$pre2[$x] = preg_replace("/([^\n]{".$wrap."})(?!<\/pre>)(?!\n)/", "$1\n", $pre2[$x]);
  
$pre1[0][$x] = "/".preg_quote($pre1[0][$x], "/")."/";
  }

  return
preg_replace($pre1[0], $pre2, $string);
}

?>

You might ask, why not just use:
<?php $string = str_replace("\n", "<br />", $string); ?>

... and prevent double spacing that way by actually *replacing* the \n with <br />, whereas nl2br() *inserts* a <br />.

Well, the answer is, doing it that way makes all the HTML output appear on a single line!  Ugly, to say the least.  The function above will keep your HTML source output formatted the same way you input it. :)
matt at mullenweg dot com
15-Oct-2002 10:23
I put together a little function to convert multiple line breaks into XHTML paragraph tags. It also changes newlines within the psuedo-paragraphs to <br />. This should be well suited to CMS where (in my case) you don't want the client to deal with *any* HTML but you still want proper paragraphs for your pages.

USAGE: You can write your text just like I have here, using the enter key as the only formatting tool. This can probably be made more efficient and I'll keep an updated (and unmangled) version of it at
http://www.photomatt.net/scripts/autop

<nl_langinfonumber_format>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT