PHP

How To Replace \n With Br In PHP?

Hello all! In this article, we will talk about how to replace \n with br in php. it's simple example of replace n with br in php. you will learn php replace n with new line. it's simple example of php replace r n with newline. Let's see bellow example php replace \n with br.

  • 4.5/5.0
  • Last updated 05 September, 2022
  • By Admin

Sometime, we took a textarea and use enter information with new lines and all. Then after when he wants to show entered details then we have to show them exactly what he enter like with enter and space all. So textarea by default adding "\n" to content so you have to convert "\n" to newline. so here we will use nl2br() function and str_replace() function to replace \n to br.

So, let's see both example one by one.

Example 1: PHP Replace n with br using nl2br()

index.php

<?php
$desc = "Line one \n Line two \n Line three \n Live four \n Line five ";
echo nl2br($desc);
?>

Output

Line one
Line two
Line three
Live four
Line five
Example 2: PHP Replace n with br using str_replace()

index.php

<?php
$desc = "Line one \n Line two \n Line three \n Live four \n Line five ";
echo str_replace("\n", "<br />", $desc);
?>

Output

Line one
Line two
Line three
Live four
Line five

I hope it can help you...