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

Updated: January 9, 2024 By: Guest Contributor Post a comment

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.