nl2br

(PHP 4, PHP 5, PHP 7)

nl2brВставляет HTML-код разрыва строки перед каждым переводом строки

Описание

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

Возвращает строку string, в которой перед каждым переводом строки (\r\n, \n\r, \n и \r) вставлен '<br />' или '<br>'.

Список параметров

string

Входная строка.

is_xhtml

Использовать ли совместимые с XHTML переводы строк или нет.

Возвращаемые значения

Возвращает измененную строку.

Примеры

Пример #1 Пример использования nl2br()

<?php
echo nl2br("foo - это вам не\n bar");
?>

Результат выполнения данного примера:

foo - это вам не<br />
 bar

Пример #2 Генерирование корректной HTML-верстки с помощью параметра is_xhtml

<?php
echo nl2br("Привет!\r\nЭтой мой HTML-документ"false);
?>

Результат выполнения данного примера:

Привет!<br>
Этой мой HTML-документ

Пример #3 Различные разделители строк

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

Результат выполнения данного примера:

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

Список изменений

Версия Описание
5.3.0 Добавлен необязательный параметр is_xhtml.

Смотрите также

  • htmlspecialchars() - Преобразует специальные символы в HTML-сущности
  • htmlentities() - Преобразует все возможные символы в соответствующие HTML-сущности
  • wordwrap() - Переносит строку по указанному количеству символов
  • str_replace() - Заменяет все вхождения строки поиска на строку замены

Коментарии

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 );
?>
2005-01-30 19:28:13
http://php5.kiev.ua/manual/ru/function.nl2br.html
Автор:
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);
}
?>
2006-03-09 15:28:48
http://php5.kiev.ua/manual/ru/function.nl2br.html
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
2007-02-23 06:12:39
http://php5.kiev.ua/manual/ru/function.nl2br.html
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.
2007-08-26 02:03:24
http://php5.kiev.ua/manual/ru/function.nl2br.html
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 ).
2008-04-01 21:34:36
http://php5.kiev.ua/manual/ru/function.nl2br.html
Автор:
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
2008-10-29 09:41:41
http://php5.kiev.ua/manual/ru/function.nl2br.html
for bbcode :

<?php
$message 
nl2br(preg_replace('#(\\]{1})(\\s?)\\n#Usi'']'stripslashes($message)));
?>
2012-05-30 00:45:48
http://php5.kiev.ua/manual/ru/function.nl2br.html
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.
2014-01-28 21:15:57
http://php5.kiev.ua/manual/ru/function.nl2br.html
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);
}
?>
2014-06-10 11:46:48
http://php5.kiev.ua/manual/ru/function.nl2br.html
I test empirically this function nl2br and nl2br2 (create by ngkongs at gmail dot com).
Both work nice with different ASCII chars for linebreak, but the function nl2br2 is faster than nl2br.

nl2br2 ~ 0.0000309944153 s
nl2br  ~ 0.0011141300201 s

The function nl2br2:
<?php 
function nl2br2($string) { 
 
$string str_replace(array("\r\n""\r""\n"), "<br />"$string); 
  return 
$string

?>
2015-09-17 15:36:28
http://php5.kiev.ua/manual/ru/function.nl2br.html
Автор:
This is example with "\R" regex token which matches any unicode newline character.
"u" flag treate strings as UTF-16. Which is optional, depending on your use case.

<?php

public function nl2br($string)
{
  return 
preg_replace('/\R/u''<br/>'$string);
}

?>

NOTE:
preg_replace versions are much slower than using str_replace version or built-in nl2br. 
Check out pcre.backtrack_limit php.ini setting for information about PCRE limit. It's good to know.

Some PHP7 benchmarks:
<?php 

// nl2br()

function nl2br_str($string) {
  return 
str_replace(["\r\n""\r""\n"], '<br/>'$string);
}

function 
nl2br_preg_R($string)
{
  return 
preg_replace('/\R/u''<br/>'$string);
}

function 
nl2br_preg_rnnr($string)
{
  return 
preg_replace('/(\r\n|\n|\r)/''<br/>'$string);
}

?>

 # nl2br
 ## Time: 0.02895712852478 s

 # nl2br_str
 ## Time: 0.027923107147217 s

 # nl2br_preg_R
 ## Time: 0.13350105285645 s

 # nl2br_preg_rnnr
 ## Time: 0.14213299751282 s
2016-05-02 10:02:02
http://php5.kiev.ua/manual/ru/function.nl2br.html
I just spent a whole day trying to figure out why my textarea $_POST was not getting <br /> tags added by nl2br().  So for others

<?php filter_input(INPUT_POST'text'FILTER_SANITIZE_SPECIAL_CHARS); ?> returns newlines as  &#13; and &#10; so nl2br will miss them.

rather use <?php filter_input(INPUT_POST'text'FILTER_SANITIZE_STRING); ?> and newlines will remain intact so nl2br will pick them up.
2017-08-16 16:07:22
http://php5.kiev.ua/manual/ru/function.nl2br.html
If you write code that is to run in browser AND on the shell, this function could be useful. It uses PHP_EOL or <br /> depending on the platform it runs:

<?php
function nl($string) {
  if(isset(
$_SERVER['SHELL'])) return preg_replace('/\<br(\s*)?\/?\>/i'PHP_EOL$string);
  return 
nl2br($string);
}

print 
nl("One\nTwo<br>Three\r\nFour<br />Five
Six" 
PHP_EOL);
?>
2017-11-07 17:39:45
http://php5.kiev.ua/manual/ru/function.nl2br.html
Автор:
double quotes !== single quotes

php > echo nl2br('\r\n');
\r\n
php > echo nl2br("\r\n");
<br />
2018-11-16 21:09:21
http://php5.kiev.ua/manual/ru/function.nl2br.html
Автор:
Let's say a form text field does contain:
 test line number 1
 test line number 2

To remove all the line breaks and split the input into an array:

$input_from_text_field = preg_replace('#[\r\n]#','',nl2br($input_from_text_field,false));
$lines = explode("<br>",$input_from_text_field);

$lines will now be an array where $lines[0] = "test line number 1" and so on.
2020-01-03 01:57:55
http://php5.kiev.ua/manual/ru/function.nl2br.html
This is a simple trick to transform newlines to paragraph a $string :

<?php 
$string_with_paragraphs 
"<p>".implode("</p><p>"explode("\n"$string))."</p>";
?>

By exploding on new lines & adding end & begin for p, it's easy to concat with <p>.

You can bring it to a function :

<?php
function nl2p($string) {
    return 
$string_with_paragraphs "<p>".implode("</p><p>"explode("\n"$string))."</p>";
}
?>
2020-06-29 23:03:00
http://php5.kiev.ua/manual/ru/function.nl2br.html
Автор:
Consider using CSS's `white-space: pre-line;` instead, it does the same thing as nl2br().
2022-12-12 14:55:33
http://php5.kiev.ua/manual/ru/function.nl2br.html

    Поддержать сайт на родительском проекте КГБ