nl2br

(PHP 4, PHP 5, PHP 7, PHP 8)

nl2brInserta saltos de línea HTML antes de todas las nuevas líneas de un string

Descripción

nl2br(string $string, bool $is_xhtml = true): string

Devuelve el parámetro string con un <br /> o <br> insertado antes de cada nueva línea. (\r\n, \n\r, \n y \r).

Parámetros

string

El string de entrada.

is_xhtml

Si utilizar saltos de línea compatibles con XHTML o no.

Valores devueltos

Devuelve el string alterado.

Ejemplos

Ejemplo #1 Usar nl2br()

<?php
echo nl2br("foo no es\n bar");
?>

El resultado del ejemplo sería:

foo no es<br />
 bar

Ejemplo #2 Generar marcado HTML válido utilizando el parámetro is_xhtml

<?php
echo nl2br("Bienvenido\r\nEste es mi documento HTML", false);
?>

El resultado del ejemplo sería:

Bienvenido<br>
Este es mi documento HTML

Ejemplo #3 Varios separadores de nueva línea

<?php
$cadena
= "Esto\r\nes\n\runa\ncadena\r";
echo
nl2br($cadena);
?>

El resultado del ejemplo sería:

Esto<br />
es<br />
una<br />
cadena<br />

Historial de cambios

Versión Descripción
5.3.0 Se agregó el parámetro opcional is_xhtml. Antes de esta versión, siempre se insertaba '<br />'.

Ver también

  • htmlspecialchars() - Convierte caracteres especiales en entidades HTML
  • htmlentities() - Convierte todos los caracteres aplicables a entidades HTML
  • wordwrap() - Ajusta un string hasta un número dado de caracteres
  • str_replace() - Reemplaza todas las apariciones del string buscado con el string de reemplazo

add a note

User Contributed Notes 6 notes

up
130
CGameProgrammer at gmail dot com
20 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
95
ngkongs at gmail dot com
18 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
49
N/A
16 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
18
fquffio at live dot it
11 years 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
12
aabaev
6 years ago
double quotes !== single quotesphp > echo nl2br('\r\n');\r\nphp > echo nl2br("\r\n");<br />
up
8
Anders Norrbring
19 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     />.<?phpfunction br2nl($text){    return  preg_replace('/<br\\s*?\/??>/i', '', $text);}?>
To Top