PHP

Using Line Breaks

How can a line break be used within HTML? That's easy: with the <br /> HTML element. However, what if there is data with \n or \r\n line breaks? Search and replace comes to mind; however, it is much easier to use a built-in PHP function: nl2br(). This parses a string and converts all line breaks to <br /> elements, as the preceding script shows.

nl2br function syntax

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

This function accept two parameters:

  1. The input string
  2. Whether to use XHTML compatible line breaks or not.
And returns the altered string.

Newline to break: Adding <br /> Elements at Every Line Break

<?php
  $input = "One\nTwo\r\nThree";
  echo nl2br($input);
?>

Outputs the HTML:

One<br />
Two<br />
Three

As you can see, the line breaks are still there, but the <br /> elements were added.

Generating valid HTML markup using the is_xhtml parameter

<?php
  $input = "One\nTwo\r\nThree";
  echo nl2br($input,false);
?>

Outputs the HTML:

One<br>
Two<br>
Three
by BrainBellupdated
Advertisement: