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);

Use Contact Form 7 to collect business leads and enquiries? I created Storage for Contact Form 7 plugin which stores them safely in WordPress database.

Get it now for only $19 →

4 Comments

  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+”.

Leave a Reply