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 isn't\n bar");
?>

上の例の出力は以下となります。

foo isn't<br />
 bar

例2 is_xhtml パラメータの使用による、妥当な HTML 形式のマークアップの生成

<?php
echo nl2br("Welcome\r\nThis is my HTML document"false);
?>

上の例の出力は以下となります。

Welcome<br>
This is my HTML document

例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 パラメータが追加されました。 以前のバージョンでは、杖に '<br />' が挿入されていました。

参考

  • htmlspecialchars() - 特殊文字を HTML エンティティに変換する
  • htmlentities() - 適用可能な文字を全て HTML エンティティに変換する
  • wordwrap() - 指定した文字数で文字列を分割する
  • str_replace() - 検索文字列に一致したすべての文字列を置換する

add a note add a note

User Contributed Notes 11 notes

up
67
CGameProgrammer at gmail dot com
11 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
31
N/A
7 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
27
ngkongs at gmail dot com
9 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
11
fquffio at live dot it
1 year 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
4
leo dot mauro dot desenv at gmail dot com
8 months ago
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;
}
?>
up
11
Anders Norrbring
10 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
6
blacknine313 at gmail dot com
8 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
Justinas M.
23 days ago
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
up
-10
j dot mons54 at gmail dot com
3 years ago
for bbcode :

<?php
$message
nl2br(preg_replace('#(\\]{1})(\\s?)\\n#Usi', ']', stripslashes($message)));
?>
up
-9
darenschwenke at yahoo dot com
2 years 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
-20
hyponiq at gmail dot com
8 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.
To Top