How to Replace \n with br in PHP?

Today now in this article, i will be talk about how we can replace \n with br in php. We know that it’s simple example of replace n with the br in php. From here you will learn php replace n with new line. So it’s simple example of php replace r n with newline. Let’s see the bellow example php replace \n with br.

Sometime, you took a textarea and the user enter information with new lines and all. Then after that we wants to show entered details then we have to show them exactly what he enter as like with enter and space all. So in textarea by default adding “\n” to content so we need to convert “\n” to newline.

So here i will use nl2br() function and str_replace() function to replace \n to br.

So, let’s and see both example one by one.

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


$desc = "Line one \n Line two \n Line three \n Live four \n Line five ";
echo nl2br($desc);
Example 2: PHP Replace n with br using str_replace()


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

Read Also: How To Take Photo In Webcam and Save From Camera Laravel 9 ?

Thanks for read. I hope it help you. For more you can follow us onĀ facebook


About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →