Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : String Functions : nl2br

nl2br

Inserts HTML line breaks before all newlines in a string (PHP 4, PHP 5)
string nl2br ( string string )

Example 2422. using nl2br()

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

The above example will output:

foo isn't<br />
bar

Related Examples ( Source code ) » nl2br



Code Examples / Notes » nl2br

chayden

Using buzoganylaszlo at yahoo dot com simple nl2p function, I've written a more HTML compliant function to deal with line breaks ...
<?php
/* FORMATS LINE BREAKS WITH PROPER HTML TAGS */
function format_html($content)
{
 $content = "

" . str_replace("\r\n", "<br/>", $content) . "";
 $content = "" . str_replace("<br/><br/>", "

", $content) . "";
 return "" . str_replace("<br/><li>", "<li>", $content) . "";
}
?>
Here is an example of its use ...
<?php
/* CONTENT TO BE PROCCESSED */
$content = "This is a\r\nline break.\r\n\r\nAnd this is a new paragraph.";
/* USE OF format_html FUNCTION */
/* NOTE: If you want 100% proper HTML tags, you'll need to add a closing paragraph tag () as shown below. */
echo format_html("$content");
?>
The above will print ...


This is a
<br/>line break.


And this is a paragraph.


silya

Trouble was with file function when long tags where broken by \r\n and function strip_tags worked not correctly with every element of array. This step prepare string from file for using function file and then strip_tags. (For example, html file generated by M$ Word)
<?php
$str = file_get_contents($filename);
$str = str_replace("\r\n", "\n", $str);
$opentag = 0;
$nl = 0;
for($i = 0; $i < strlen($str); $i++)
{
  if($opentag == 1 && $str[$i] == "\n")
  {
     $str[$i] = '  ';
     continue;
  }
  if($str[$i] == '<')
     $opentag = 1;
  elseif($str[$i] == '>')
     $opentag = 0;
  else ;
}
?>


ngkongs

to replace all linebreaks to <br />
the best solution (IMO) is:
function nl2br2($string) {
$string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string);
return $string;
}
because each OS have different ASCII chars for linebreak:
windows = \r\n
unix = \n
mac = \r
works perfect for me


buzoganylaszlo

There is a simple nl2p function:
<?php
function nl2p($text) {
 return "

" . str_replace("\n", "

", $text) . "";
}
?>


mike

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

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

', "\r"), '', $text);
     return $text;
  } // end nl2p
 /**
   * expanding on the nl2p tag above to convert user contributed
   * <br />'s to

'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

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

', "

\n"), '', $text);
     return $text;
}
This is all code from Back-End CMS (http://www.back-end.org), a template based gpl php/mysql cms.
Mike


php

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.


17-jan-2005 08: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 '  

'."\n";
echo nl2br_indent($str, 4)."\n";
echo '  '."\n";
echo '</html>'."\n";
?>
will return:
<html>
 


   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.
 
</html>
- $str is indented by 4 spaces.


nacho dot exr

Simple function that converts more than one
,<br/>,<br />... to a

. Maybe it's useful for someone =)
function br2p($string)
{
 return preg_replace('#

[\n\r\s]*?#m', '', '

'.preg_replace('#(<br\s*?/?>){2,}#m', '

', $string).'');
}
Useful used with nl2br:
br2p(nl2br(...));


anders norrbring

Seems like I was a bit too quick and left out the vital part, and I also missed to escape the slashes in the post...
<?php
function br2nl($text)
{
return  preg_replace('/<br\\\\s*?\\/??>/i', "\\n", $text);
}
?>


x against capital x

Regarding last post by admin at ninthcircuit, I think:
"rather than get into nasty regular expressions" === "I don't understand regular expressions"
No offense, but please be aware that kristen's solution is much more robust.  The ninthcircuit solution will miss cases when there are differences in case (e.g., BR instead of br) and when there is more than one space between the r and the / (e.g., <br    />).
We all like robust code, don't we?


jonasnicklas

Re: emailfire
The function emailfire posted is missing some backslashes, a better alternative to it is:
<?php
$foo = "This\nis a\r\ntest\rmessage";
function nl2brr($text)
{
return preg_replace("/\r\n|\n|\r/", "
", $text);
}
echo nl2brr($foo);
# Output: This
is a
test
message
?>
I put both functions in a for-loop and surprisingly preg_replace is a lot faster, I assume this is because str_replace will search the string several times. If you know what kind of breaks (Windows/Unix) you are expecting it is obviously better to use str_replace.
A note: Internet Explorer does not have any XHTML support, even browsers that DO have XHTML support (such as Firefox or Opera) will not parse pages as XHTML unless told so via a Header (for example through php's header function, like <?php header(Content-type: application/xhtml+xml); ?>), the tag <br /> is invalid in HTML 4. Since all browsers show it correctly anyway (though according to the specification they shouldn't), you could simply not care...


hyponiq

On the contrary, <b>mark at dreamjunky.comno-spam</b>, this function is rightfully named.  Allow me to explain.  Although it does re-add the line break, it does so in an attempt to stay standards-compliant with the W3C recommendations for code format.
According to said recommendations, a new line character must follow a line break tag.  In this situation, the new line is not removed, but a break tag is added for proper browser display where a paragraph isn't necessary or wanted.


tom dot crawford

Note to foltscane at yahoo dot com
Wouldn't it be easier to do this:
$encoded_string = nl2br( htmlentities( $string_to_encode ) );


greywyvern - greywyvern - com

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. :)


cgameprogrammer

It's important to remember that this function does NOT replace newlines with
tags. Rather, it inserts a
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 );


asentis

If you want to respect W3C, you can use this function :
<?php
function nl2p($str)
{
 return str_replace('

', '', '

' . preg_replace('#\n|\r#', '$0

', $str) . '');
}
?>
Cya :)


thunberg

I wrote this because I wanted users to be able to do basic layout formatting by hitting enter in a textbox but still wanted to allow HTML elements (tables, lists, etc). The problem was in order for the output to be correct with nl2br the HTML had to be "scrunched" up so newlines wouldn't be converted; the following function solved my problem so I figured I'd share.
<?php
function nl2br_skip_html($string)
{
// remove any carriage returns (mysql)
$string = str_replace("\r", '', $string);
// replace any newlines that aren't preceded by a > with a <br />
$string = preg_replace('/(?<!>)\n/', "<br />\n", $string);
return $string;
}
?>


foltscane

I was interested in changing \n to
but then still having htmlentities enforced inbetween these added
s. So I wrote this simple textentities which will do just that.
function textentities($s)
{
while($sp = strpos($s,"\n"))
{
echo htmlentities(substr($s,0,$sp))."
";
$s = substr($s,$sp+1,strlen($s));
}
echo htmlentities($s);
}


matt

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


godfrank domain-is msn tld-is com

I have modified my function found in the previous post.
It now uses preg_replace() which should technically be faster than ereg_replace(). You can also specify what you want to replace "\r\n" with. If you use the function with only one parameter, it will use '<br />' by default.
<?php
function nl2brStrict($text, $replacement = '<br />')
{
return preg_replace("((\r\n)+)", trim($replacement), $text);
}
?>


freedman

here's a modified version that allows the addition of style tags to the

marker
function nl2p($str,$addtag='') {
return str_replace('<p'.$addtag.'>', '', '<p'.$addtag.'>' . preg_replace('#\n|\r#', '$0<p'.$addtag.'>', $str) . '');
}
$x = "abc\ndef"
echo nl2p($x);  // outputs

abc\n

def
echo nl2p($x,' style="text-align:justify"');
// outputs <p style="text-align:justify">abc\n<p style="text-align:justify">def


webkami

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 :)


moore

Here a litle function that might come handy one time:
It gives back a String and adds a
(you can change it to <br />) to every line end. And it adds $num blanks to the front of the next line.
<?php
function nl2brnl($text, $num)
 {
  return preg_replace("/\\r\\n|\\n|\\r/", sprintf("% -".(5+$num)."s","
\\n"), $text);
 }
$a = " one\\n two\\r\\n three";
$b = nl2brnl($a, 2);
var_dump($b);
/* output will be:
string(30) " one
two
three"
*/
echo "  

\\n  ";
echo $b
/* output will be:
 


  one
two
three
*/
?>
Is helpfull for avouding code_soup.


jochem

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


btm

Comment on emailfire at gmail dot com nl2brr. It should be:
<? return str_replace(array("\r\n", "\n", "\r"), "
", $text); ?>
You've forgotten the backslashes.


php

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 );
}
?>


webmaster

based on previous notes, a generalist function that works with any <tag>...</tag>, and its ^-1. (use it with "li", for example) :
<?php
function nl2any($string, $tag = 'p', $feed = '') {
 // making tags
 $start_tag = "<$tag" . ($feed ? ' '.$feed : '') . '>' ;
 $end_tag = "</$tag>" ;
 
 // exploding string to lines
 $lines = preg_split('`[\n\r]+`', trim($string)) ;
 
 // making new string
 $string = '' ;
 foreach($lines as $line)
   $string .= "$start_tag$line$end_tag\n" ;
 
 return $string ;
}

function any2nl($string, $tag = 'p') {
 //exploding
 preg_match_all("`<".$tag."[^>]*>(.*)</".$tag.">`Ui", $string, $results) ;
 // reimploding without tags
 return implode("\n", array_filter($results[1])) ;
}
?>
I just had a problem when trying "`<$tag[^>]*>(.*)</$tag>`Ui" regexp string, I can't figure out why.


admin

As stated in the manual above, PHP's nl2br() feature only puts a "<br />" tag before each newline ("\n"). So -- if you intend to code a br2nl() function for yourselves, all you have to do is remove every occurence of "<br />" or "
".
Rather than get into nasty regular expressions to accomplish this, just use what PHP has built in already --  str_replace():
<?php
   /* br2nl for use with HTML forms, etc. */
   function br2nl($text)
   {
       /* Remove XHTML linebreak tags. */
       $text = str_replace("<br />","",$text);
       /* Remove HTML 4.01 linebreak tags. */
       $text = str_replace("
","",$text);
       /* Return the result. */
       return $text;
   }
?>
The final result from this function being called is whatever was entered before XHTML/HTML linebreaks were added.
All newlines are preserved by default, as per PHP ln2br() specification. Since the code above preserves newlines also, you can expect your data to reappear in the same way it was entered.
Hope this helps.


spertica

An easy way to get HTML formatted with
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
in newvar
     echo $new_text; // print out HTML formatted text
     unset($string_text, $new_text); // clear all vars to unload memory
?>


kristen

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);
}


webkami

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;
}


phpdoc

@flashyeu at yahoo dot com:
It's a newline. Browsers show newlines in the HTML code as spaces, unless in a <pre> tag. Try this:
<?php
header("Content-Type: text/plain");
$str = 'One plus one is two
Two plus two is four.';
$str = nl2br($str);
$str = strip_tags($str);
print str_replace(' ','',$str);
//out put Oneplusoneistwo Twoplustwoisfour.
?>


sebastian

// Convert only
<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.


fili

<?php
function p2nl ($str) {
return preg_replace(array("/<p[^>]*>/iU","/<\/p[^>]*>/iU"),
array("","\n"),
$str);
}
$string = "0

1

23";
var_dump(p2nl($string));
/*
Output:

string(6) "01
2
3"
*/
?>


moester

<?php
function nls2p($str)
{
 return str_replace('

', '', '

'
       . preg_replace('#([\r\n]\s*?[\r\n]){2,}#', '$0

', $str)
       . '');
}
?>
Turns two or more consecutive newlines (separated by possible white space) into a

....
Pass result to regular nl2br() to add <br/> to remaining nl's, eg,
<?php
echo nl2br(nls2p("Paragraph1\n\nParagraph2\n line1\n line2\n"));
?>
result:


Paragraph1


Paragraph2<br/>
line1<br/>
line2<br/>


flashyeu

<?php
$str = 'One plus one is two
Two plus two is four.';
$str = nl2br($str);
$str = strip_tags($str);
print str_replace(' ','',$str);
//out put Oneplusoneistwo Twoplustwoisfour.
?>
What's char between 'Oneplusoneistwo' and 'Twoplustwoisfour.'
It not's whitespaces. What's it?


Change Language


Follow Navioo On Twitter
addcslashes
addslashes
bin2hex
chop
chr
chunk_split
convert_cyr_string
convert_uudecode
convert_uuencode
count_chars
crc32
crypt
echo
explode
fprintf
get_html_translation_table
hebrev
hebrevc
html_entity_decode
htmlentities
htmlspecialchars_decode
htmlspecialchars
implode
join
levenshtein
localeconv
ltrim
md5_file
md5
metaphone
money_format
nl_langinfo
nl2br
number_format
ord
parse_str
print
printf
quoted_printable_decode
quotemeta
rtrim
setlocale
sha1_file
sha1
similar_text
soundex
sprintf
sscanf
str_getcsv
str_ireplace
str_pad
str_repeat
str_replace
str_rot13
str_shuffle
str_split
str_word_count
strcasecmp
strchr
strcmp
strcoll
strcspn
strip_tags
stripcslashes
stripos
stripslashes
stristr
strlen
strnatcasecmp
strnatcmp
strncasecmp
strncmp
strpbrk
strpos
strrchr
strrev
strripos
strrpos
strspn
strstr
strtok
strtolower
strtoupper
strtr
substr_compare
substr_count
substr_replace
substr
trim
ucfirst
ucwords
vfprintf
vprintf
vsprintf
wordwrap
eXTReMe Tracker