Open In App

How to insert a line break in PHP string ?

Last Updated : 07 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In this article, we will discuss how to insert a line break in a PHP string. We will get it by using the nl2br() function. This function is used to give a new line break wherever ‘\n’ is placed.

Syntax:

nl2br("string \n");

where the string is the input string.

Example 1: PHP Program to insert a line break in a string.

<?php

// Insert a new line break
echo nl2br("This is first line \n This is second line");

?>

Output
This is first line <br />
 This is second line

Example 2:

<?php

// Insert a line break with new line
echo nl2br("This is first line \n This is second "
   + "line \n This is third line \n This is fourth line");

?>

Output
This is first line <br />
 This is second line <br />
 This is third line <br />
 This is fourth line

Using Nowdoc Syntax

Using Nowdoc syntax in PHP, you can insert a line break by defining a multi-line string. This syntax treats everything literally, without parsing variables or special characters.

Example:

<?php
$string = <<<'EOD'
Hello,
World!
EOD;
echo $string . PHP_EOL; // Outputs to the console
?>

Output
Hello,
World!

Using PHP_EOL Constant

The PHP_EOL constant in PHP represents the end-of-line character appropriate for the platform PHP is running on (e.g., “\n” on Unix-like systems, “\r\n” on Windows). You can use this constant to insert platform-independent line breaks in a string.

Example:

<?php
function insertLineBreakUsingEOL($string) {
    return str_replace("\n", PHP_EOL, $string);
}

$inputString = "Hello,\nWorld!";
$formattedString = insertLineBreakUsingEOL($inputString);

echo nl2br($formattedString);  
?>

Output
Hello,<br />
World!

Using str_replace()

The str_replace() function in PHP can replace all occurrences of a substring within a string. You can use this function to replace the newline character \n with <br /> tags for HTML output.

Example:

<?php
function insertLineBreakUsingStrReplace($string) {
    return str_replace("\n", "<br />", $string);
}

$inputString = "This is the first line \nThis is the second line";
$formattedString = insertLineBreakUsingStrReplace($inputString);

echo $formattedString;
?>

Output
This is the first line <br />This is the second line




Similar Reads

three90RightbarBannerImg