Remove new lines from string in PHP

In PHP, you can remove newlines from a string using several built-in functions. The most common approaches are using preg_replace() for pattern-based removal and str_replace() for simple character replacement.

Using preg_replace()

The preg_replace() function removes all types of newlines using regular expressions ?

<?php
    $str = "Demo
    text for
    reference";
    echo "Original string with newlines:<br>";
    echo nl2br($str);
    
    $str = preg_replace('~[\r<br>]+~','', $str);
    echo "<br>\nAfter removing newlines:<br>";
    echo nl2br($str);
?>
Original string with newlines:
Demo<br />
    text for<br />
    reference

After removing newlines:
Demo    text for    reference

Using str_replace()

The str_replace() function targets specific newline characters directly ?

<?php
    $str = "Demo
    text";
    echo "Original string with newlines:<br>";
    echo nl2br($str);
    
    $str = str_replace(array("<br>", "\r"), '', $str);
    echo "<br>\nAfter removing newlines:<br>";
    echo nl2br($str);
?>
Original string with newlines:
Demo<br />
    text

After removing newlines:
Demo    text

Comparison

Method Best For Performance
preg_replace() Complex patterns, multiple consecutive newlines Slower
str_replace() Simple character replacement Faster

Conclusion

Use str_replace() for simple newline removal and preg_replace() when dealing with complex patterns or multiple consecutive newlines. Both methods effectively clean strings for display or processing.

Updated on: 2026-03-15T08:23:27+05:30

755 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements