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

  1. <span class="pun">&lt;?</span><span class="pln">php</span>
  2. <span class="pln">$desc </span><span class="pun">=</span><span class="pln"> </span><span class="str">"Line one \n Line two \n Line three \n Live four \n Line five "</span><span class="pun">;</span>
  3. <span class="pln">echo nl2br</span><span class="pun">(</span><span class="pln">$desc</span><span class="pun">);</span>
  4. <span class="pun">?&gt;</span>

Output

  1. <span class="typ">Line</span><span class="pln"> one</span>
  2. <span class="typ">Line</span><span class="pln"> two</span>
  3. <span class="typ">Line</span><span class="pln"> three</span>
  4. <span class="typ">Live</span><span class="pln"> four</span>
  5. <span class="typ">Line</span><span class="pln"> five</span>
Example 2: PHP Replace n with br using str_replace()

index.php

  1. <span class="pun">&lt;?</span><span class="pln">php</span>
  2. <span class="pln">$desc </span><span class="pun">=</span><span class="pln"> </span><span class="str">"Line one \n Line two \n Line three \n Live four \n Line five "</span><span class="pun">;</span>
  3. <span class="pln">echo str_replace</span><span class="pun">(</span><span class="str">"\n"</span><span class="pun">,</span><span class="pln"> </span><span class="str">"&lt;br /&gt;"</span><span class="pun">,</span><span class="pln"> $desc</span><span class="pun">);</span>
  4. <span class="pun">?&gt;</span>

Output

  1. <span class="typ">Line</span><span class="pln"> one</span>
  2. <span class="typ">Line</span><span class="pln"> two</span>
  3. <span class="typ">Line</span><span class="pln"> three</span>
  4. <span class="typ">Live</span><span class="pln"> four</span>
  5. <span class="typ">Line</span><span class="pln"> five</span>

I hope it can help you...