Remove new lines from string in PHP

PHPServer Side ProgrammingProgramming

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\n]+~','', $str);
   echo "\n".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("\n", "\r"), '', $str);
   echo "\n".nl2br($str);
?>

Output

This will produce the following output−

Demo<br />
   <br />
text
Demo text
raja
Published on 27-Dec-2019 07:47:05
Advertisements