Jump to: navigation, search

Php nl2br

From w3cyberlearnings

Contents

PHP function nl2br

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

Syntax nl2br

  • string: string input.
  • is_xhtml: set to true for XHTML compatible line breaks or not
nl2br(string,is_xhtml);

Example 1

<?php
$str ="I will\n He will\n She will\n do it";
echo nl2br($str);
?>

Output

I will<br />
 He will<br />
 She will<br />
 do it

Example 2

<?php
$str ="I'm last\r She's last\r He's last";
echo nl2br($str);

?>

Output

I'm last<br />
 She's last<br />
 He's last

Example 3: get file content and apply the nl2br function

  • Get file content from a file and display them to the page.
3.txt file
------------------------
I go to school with you
She works all day today
Lost all the opportunity
Give all my hope to you

<?php

$file_content = file_get_contents('3.txt');
echo nl2br($file_content);

?>

Output

I go to school with you<br />

She works all day today<br />

Lost all the opportunity<br />

Give all my hope to you<br />

Example 4: set the is_xhtml parameter value to false

<?php
$str ="She loves it\nHe needs it";
echo nl2br($str,false);
?>

Output

She loves it<br>
He needs it

Related Functions


Navigation
Web
SQL
MISC
References