How to Replace \n with br in PHP?

In this blog, we will be going to learn how to replace \n with br tag in PHP. This is going to be very simple and easy. This can be used when you have data in textarea and you want to show to your website but it does not give any new line in PHP. 


There are two functions that we will be using to replace \n with br and those are nl2br() function and str_replace() function.


Let's start with examples,


PHP Replace \n with br using nl2br()


Code:


<?php

  

$desc = "This is thecodingdev.com. \n We provide solutions for PHP, Laravel, SQL, Stock Market,etc.  \n Check our blog regularly for the latest updates. \n We want to give everything free. ";

  

echo nl2br($desc);


Output:


This is thecodingdev.com. 

We provide solutions for PHP, Laravel, SQL, Stock Market, etc. 

Check our blog regularly for the latest updates.

We want to give everything free. 



PHP Replace \n with br using str_replace()


Code:


<?php

  

$desc = "This is thecodingdev.com. \n We provide solutions for PHP, Laravel, SQL, Stock Market,etc.  \n Check our blog regularly for the latest updates. \n We want to give everything free. ";

  

echo str_replace("\n", "<br />", $desc);


Output:


This is thecodingdev.com. 

We provide solutions for PHP, Laravel, SQL, Stock Market, etc. 

Check our blog regularly for the latest updates.

We want to give everything free. 



I hope this will help in your projects. If you have any doubts, let me know in the comments.