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>
<html>
<head>
<title>nl2br() Function Example</title>
</head>
<body>
<h1>Input Text</h1>
<form action="display.php" method="post">
<textarea name="input_text" rows="5" cols="50"></textarea>
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
PHP script to display the text with line breaks (display.php
):
<!DOCTYPE html>
<html>
<head>
<title>Display Text with Line Breaks</title>
</head>
<body>
<h1>Text with Line Breaks</h1>
<?php
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>
</body>
</html>
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:
Input:
Hello
This is a multi-line
text.
Output:
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.