PHP nl2br() Function Example Easy Tutorial

The nl2br() function in PHP is used to insert HTML line breaks <br> before all new lines in a string. It’s commonly used to display text from a text area or a text file in HTML while preserving line breaks. Here’s a tutorial-style example to demonstrate how to use the nl2br() function:

Suppose you have a form with a text area where users can input some text with line breaks. After submitting the form, you want to display the text on a webpage while maintaining the line breaks using the nl2br() function.

HTML form (index.html):

<!DOCTYPE html>
    <title>nl2br() Function Example</title>
    <h1>Input Text</h1>
    <form action="display.php" method="post">
        <textarea name="input_text" rows="5" cols="50"></textarea>
        <input type="submit" value="Submit">

PHP script to display the text with line breaks (display.php):

<!DOCTYPE html>
    <title>Display Text with Line Breaks</title>
    <h1>Text with Line Breaks</h1>
    if ($_SERVER["REQUEST_METHOD"] === "POST") {
        // Get the input text from the form
        $inputText = $_POST["input_text"];

        // Use nl2br() to convert newlines to <br> tags
        $formattedText = nl2br($inputText);

        // Display the formatted text
        echo "<p>{$formattedText}</p>";
    <a href="index.html">Back to Input</a>

In this example, we have a simple HTML form (index.html) with a text area for users to input text. When the form is submitted, the PHP script display.php receives the input, applies the nl2br() function to the input text to insert <br> tags, and then displays the formatted text on the webpage.

When users enter text with line breaks in the text area and submit the form, the displayed output will show the text with appropriate line breaks in the browser.

For example:

This is a multi-line

Hello<br>This is a multi-line<br>text.

Since the nl2br() function inserts HTML line breaks, make sure to sanitize the input if it’s coming from user input to prevent potential HTML injection vulnerabilities. You can use functions like htmlspecialchars() to do this.