Sling Academy
Home/PHP/PHP: How to convert ‘\n’ to HTML ‘br’ tag

PHP: How to convert ‘\n’ to HTML ‘br’ tag

Last updated: January 09, 2024

Introduction

Working with string manipulation is a common task in PHP development, particularly when it comes to preparing output for the web. One frequent requirement is converting newline characters to HTML line breaks. This tutorial will explore various methods to achieve this in PHP.

Utilizing nl2br Function

PHP offers a built-in function nl2br that inserts HTML line breaks before all newlines in a string. It’s the simplest method when you’re dealing strictly with Unix-style newlines.

<?php
$text = "Hello\nWorld";
$convertedText = nl2br($text, false);
echo $convertedText; // Outputs: Hello<br>
World
?>

Simple str_replace Function

The str_replace function in PHP is a straightforward way to replace all occurrences of the newline character (\n) with the HTML
tag.

<?php
$text = "Hello\nWorld";
$convertedText = str_replace("\n", "<br>", $text);
echo $convertedText; // Outputs: Hello<br>World
?>

Using preg_replace for Regular Expressions

If you need a more powerful solution that can handle different types of newlines (like \r\n on Windows), preg_replace with a regular expression is an excellent choice.

<?php
$text = "Hello\r\nWorld";
// This will match \r\n, \r, and \n newlines
$convertedText = preg_replace("/\r\n|\r|\n/", "<br>", $text);
echo $convertedText; // Outputs: Hello<br>World
?>

Combining nl2br and str_replace

If you have a mix of Unix and Windows newlines and want to convert them uniformly to <br> tags without any trailing newline characters, you can combine nl2br with str_replace.

<?php
$text = "Hello\r\nWorld";
$convertedText = nl2br($text);
$convertedText = str_replace(array("\r\n", "\n", "\r"), "", $convertedText);
echo $convertedText; // Outputs: Hello<br>World
?>

Handling Multiline Texts with Loops

Sometimes you need to process multiline texts line by line. Here’s how you can use a loop to convert newlines to
tags.

<?php
$text = "Hello\nWorld\n";
$lines = explode("\n", $text);
$convertedText = '';
foreach ($lines as $line) {
    $convertedText .= $line . "<br>";
}
echo rtrim($convertedText, "<br>"); // Outputs: Hello<br>World
?>

Advanced Usage with Callback Functions

You can also use the preg_replace_callback function to process replacements in a more complex manner, giving you the flexibility to add conditional logic to your newline conversions.

<?php
$text = "Hello\nWorld";
$convertedText = preg_replace_callback("/\n/", function($matches) {
    // Your custom logic here
    return "<br>";
}, $text);

echo $convertedText; // Outputs: Hello<br>World
?>

Final Words

Understanding how to convert newlines to HTML <br> tags is essential for web output in PHP. As we’ve seen, there are multiple approaches depending on your specific requirements. Choose the one that best fits your project’s needs and allows for readable and maintainable code.

Next Article: PHP: How to create multiline strings

Previous Article: Single-Quotes and Double-Quotes in PHP

Series: Working with Numbers and Strings in PHP

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array