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: 2019-12-27T07:47:05+05:30

640 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements