How to Remove All Line Breaks from Text Using Regex

If you are generating <meta> description tags automatically (e.g. by including all headings of the document), chances are that you’re extracting it from various sources of content that contain different HTML elements and line breaks in them. 

Here is a simple regular expression to remove all line breaks, carriage returns and tabs, and replace them with an empty space.

$text = preg_replace( '/(\r\n)+|\r+|\n+|\t+/i', ' ', $text )

It works by replacing all instances of Windows and unix line breaks and tabs with a blank space character.

Never lose a single business lead or enquiry again! Get my latest plugin Storage for Contact Form 7 now!

Buy now for only $19 →


  1. Shan says:

    Hi Kaspars,
    This really works good and saved a lot of time for me….!
    Thanks a lot….! :)

  2. Larry says:

    Sweet. Thanks man, saved me a lot of time!

  3. Zamicol says:

    Shouldn’t it be (\r\n)+|\r+|\n+?

    “+” will only apply to the immediately preceding character. “\r\n” needs to be grouped. I believe “\r\n+” is functionally equivalent to “\r\n|\n+”.

  4. Camille says:

    Cool, thanks for this! :)

    How can I make it replace line breaks with a comma instead of an empty space?

Leave a Reply