PHP 5.6.0 released

nl2br

(PHP 4, PHP 5)

nl2brFügt vor allen Zeilenumbrüchen eines Strings HTML-Zeilenumbrüche ein

Beschreibung

string nl2br ( string $string [, bool $is_xhtml = true ] )

Gibt den string mit einem vor allen Neue-Zeile-Zeichen eingefügten '<br />' oder '<br>' zurück (\r\n, \n\r, \n und \r).

Parameter-Liste

string

Die Eingabezeichenkette.

is_xhtml

Bestimmt, ob XHTML-kompatible Zeilenumbrüche verwendet werden sollen oder nicht.

Rückgabewerte

Gibt die veränderte Zeichenkette zurück.

Beispiele

Beispiel #1 Verwenden von nl2br()

<?php
echo nl2br("foo ist nicht\n bar");
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

foo ist nicht<br />
 bar

Beispiel #2 Erstellen von validem HTML-Markup unter Verwendung des is_xhtml-Parameters

<?php
echo nl2br("Willkommen\r\nDies ist mein HTML-Dokument"false);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Willkommen<br>
Dies ist mein HTML-Dokument

Beispiel #3 Verschiedene Zeilentrenner

<?php
$string 
"This\r\nis\n\ra\nstring\r";
echo 
nl2br($string);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

This<br />
is<br />
a<br />
string<br />

Changelog

Version Beschreibung
5.3.0 Der optionale is_xhtml-Parameter wurde hinzugefügt.
4.0.5 nl2br() ist nun XHTML-konform. Alle älteren Versionen geben string mit vor allen Zeilenumbrüchen eingefügtem '<br>' statt '<br />' zurück.

Siehe auch

  • htmlspecialchars() - Wandelt Sonderzeichen in HTML-Codes um
  • htmlentities() - Wandelt alle geeigneten Zeichen in entsprechende HTML-Codes um
  • wordwrap() - Bricht einen String nach einer bestimmten Anzahl Zeichen um
  • str_replace() - Ersetzt alle Vorkommen des Suchstrings durch einen anderen String

add a note add a note

User Contributed Notes 10 notes

up
22
N/A
5 years ago
Here's a more simple one:

<?php
/**
* Convert BR tags to nl
*
* @param string The string to convert
* @return string The converted string
*/
function br2nl($string)
{
    return
preg_replace('/\<br(\s*)?\/?\>/i', "\n", $string);
}
?>

Enjoy
up
14
CGameProgrammer at gmail dot com
9 years ago
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:

<?php
$Result
= str_replace( "\n", '<br />', $Text );
?>
up
5
fquffio at live dot it
2 months ago
Starting from PHP 4.3.10 and PHP 5.0.2, this should be the most correct way to replace <br /> and <br> tags with newlines and carriage returns.
<?php
/**
* Convert BR tags to newlines and carriage returns.
*
* @param string The string to convert
* @return string The converted string
*/
function br2nl ( $string )
{
    return
preg_replace('/\<br(\s*)?\/?\>/i', PHP_EOL, $string);
}
?>
(Please note this is a minor edit of this function: http://php.net/nl2br#86678 )

You might also want to be "platform specific", and therefore this function might be of some help:
<?php
/**
* Convert BR tags to newlines and carriage returns.
*
* @param string The string to convert
* @param string The string to use as line separator
* @return string The converted string
*/
function br2nl ( $string, $separator = PHP_EOL )
{
   
$separator = in_array($separator, array("\n", "\r", "\r\n", "\n\r", chr(30), chr(155), PHP_EOL)) ? $separator : PHP_EOL// Checks if provided $separator is valid.
   
return preg_replace('/\<br(\s*)?\/?\>/i', $separator, $string);
}
?>
up
6
Anders Norrbring
8 years ago
Seeing all these suggestions on a br2nl function, I can also see that neither would work with a sloppy written html line break.. Users can't be trusted to write good code, we know that, and mixing case isn't too uncommon.

I think this little snippet would do most tricks, both XHTML style and HTML, even mixed case like <Br> <bR /> and even <br            > or <br     />.

<?php
function br2nl($text)
{
    return 
preg_replace('/<br\\s*?\/??>/i', '', $text);
}
?>
up
4
ngkongs at gmail dot com
7 years ago
to replace all linebreaks to <br />
the best solution (IMO) is:

<?php
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
up
1
darenschwenke at yahoo dot com
7 months ago
This one works with br tags having attributes, in any case,
closed or  not closed, and does not double linefeeds

<?php
/**
* convert br tags to nl
*
* @param string The string to convert
* @return string The converted string
*/

function br2nl($string)
{
    return
preg_replace("/<br[^>]*>\s*\r*\n*/is", "\n", $string);
}
?>

I combine this with strip_tags() for dead simple "contenteditable" fields allowing only text and linefeeds.
up
2
blacknine313 at gmail dot com
6 years ago
After a recent post at the forums on Dev Shed, I noticed that it isn't mentioned, so I will mention it.

nl2br returns pure HTML, so it should be after PHP anti-HTML functions ( such as strip_tags and htmlspecialchars ).
up
0
j dot mons54 at gmail dot com
2 years ago
for bbcode :

<?php
$message
nl2br(preg_replace('#(\\]{1})(\\s?)\\n#Usi', ']', stripslashes($message)));
?>
up
-6
hyponiq at gmail dot com
7 years ago
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.
up
-60
billhicks at yahoo dot com
5 months ago
Your new site does not work in ie.

But you already know this and I guess you don't really care.

its all about style now - funny because this is a php site not a css/java/ajax site.

piss off!!!!!!!!!!!!!!!
To Top