PHP nl2br() Function Tutorial

beginner
12 min

PHP nl2br() Function Tutorial

Welcome, coders! Today, we're diving into the world of PHP and learning about the powerful nl2br() function. This function is a lifesaver when it comes to converting newline characters into HTML-friendly line breaks, which is crucial for displaying plain text on a web page. Let's get started!

What is the nl2br() function in PHP? πŸ’‘

The nl2br() function is a built-in PHP string function that converts newline characters (\n) into HTML line break tags (<br>). This transformation makes it possible to display text with line breaks correctly on a web page.

Why do we need nl2br()? πŸ“

When you work with text data, especially from user inputs, you often encounter newline characters. However, these characters are not recognized by HTML, and they will display as plain text. This is where the nl2br() function comes in handy, converting these newline characters into <br> tags, which HTML understands and displays as separate lines.

How to use the nl2br() function? βœ…

Using the nl2br() function is straightforward! Here's a step-by-step guide:

  1. First, you need to have a string containing newline characters.
php
$text = "This is the first line.\nThis is the second line.\nThis is the third line.";
  1. Then, you call the nl2br() function and pass the string to it.
php
$htmlText = nl2br($text);
  1. Now, the $htmlText variable contains the string with newline characters converted into <br> tags.
php
echo $htmlText; // Output: This is the first line. // <br>This is the second line. // <br>This is the third line.

Practical Example 🎯

Let's create a simple PHP script that allows users to input text and displays it with line breaks on a web page.

php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP nl2br() Example</title> </head> <body> <?php // Check if the form has been submitted if (isset($_POST['submit'])) { // Get the user input $text = $_POST['text']; // Convert newline characters to HTML line breaks $htmlText = nl2br($text); // Output the text with line breaks echo "<pre>$htmlText</pre>"; } ?> <!-- Form for user input --> <form action="" method="post"> <label for="text">Enter your text:</label> <textarea name="text" id="text" rows="10" cols="30"></textarea> <button type="submit" name="submit">Submit</button> </form> </body> </html>

This example creates an HTML form that takes user input and displays it with line breaks using the nl2br() function. Try it out yourself!

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What does the `nl2br()` function do in PHP?

That's it for today! We hope you found this tutorial helpful. Keep practicing, and you'll master the nl2br() function in no time. Stay tuned for more PHP tutorials on CodeYourCraft! πŸš€


Types:

  1. string - The nl2br() function returns a string.