Remove new lines from string in PHP


To remove newlines from the string, the code is as follows−

Example

 Live Demo

<?php
   $str = "Demo
   text for
   reference";
   echo nl2br($str);
   $str = preg_replace('~[\r
]+~','', $str);    echo "
".nl2br($str); ?>

Output

This will produce the following output−

Demo<br />
   <br />
text for <br />
<br />
reference
Demo text for reference

Example

Let us now see another example −

 Live Demo

<?php
   $str = "Demo
   text";
   echo nl2br($str);
   $str = str_replace(array("
", "\r"), '', $str);    echo "
".nl2br($str); ?>

Output

This will produce the following output−

Demo<br />
   <br />
text
Demo text

Updated on: 27-Dec-2019

425 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements