String Functions

PHP nl2br() Function

Topic: PHP String ReferencePrev|Next

Description

The nl2br() function inserts HTML line breaks before all newlines (\r\n, \n\r, \n and \r) in a string.

The following table summarizes the technical details of this function.

Return Value: Returns the modified string.
Version: PHP 4+

Syntax

The basic syntax of the nl2br() function is given with:

nl2br(string, is_xhtml);

The following example shows the nl2br() function in action.

<?php
echo nl2br("Hi, there!\nWelcome to our website.");
?>

The output of the above example will be (view source to get an idea):

Hi, there!<br />
Welcome to our website.

However in the browser you will see something like this:

Hi, there!
Welcome to our website.

Parameters

The nl2br() function accepts the following parameters.

Parameter Description
string Required. Specifies the string to work on.
is_xhtml

Optional. Specifies whether to use XHTML compatible line breaks or not. Possible values are:

  • true – Default. Inserts <br />
  • false – Inserts <br>

More Examples

Here're some more examples showing how nl2br() function actually works:

The following example inserts HTML <br> tag before newlines using is_xhtml parameter.

<?php
echo nl2br("Hi, there!\r\nWelcome to our website.", false);
?>

The output of the above example will be (view source to get an idea):

Hi, there!<br>
Welcome to our website.

However in the browser you will see something like this:

Hi, there!
Welcome to our website.

Tip: The character \r is a carrige return and \n is a line feed. The character \n is used to create a newline in UNIX, whereas \r is used in old MacOS, while in Windows the two character sequence: \r\n is used. To be on safe side use the sequence \r\n instead.

Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties