Home » Php » php – Replace multiple newlines, tabs, and spaces

php – Replace multiple newlines, tabs, and spaces

Posted by: admin April 23, 2020 Leave a comment


I want to replace multiple newline characters with one newline character, and multiple spaces with a single space.

I tried preg_replace("/\n\n+/", "\n", $text); and failed!

I also do this job on the $text for formatting.

$text = wordwrap($text, 120, '<br/>', true);
$text = nl2br($text);

$text is a large text taken from user for BLOG, and for a better formatting I use wordwrap.

How to&Answers:

In theory, you regular expression does work, but the problem is that not all operating system and browsers send only \n at the end of string. Many will also send a \r.


I’ve simplified this one:

preg_replace("/(\r?\n){2,}/", "\n\n", $text);

And to address the problem of some sending \r only:

preg_replace("/[\r\n]{2,}/", "\n\n", $text);

Based on your update:

// Replace multiple (one ore more) line breaks with a single one.
$text = preg_replace("/[\r\n]+/", "\n", $text);

$text = wordwrap($text,120, '<br/>', true);
$text = nl2br($text);


Use \R (which represents any line ending sequence):

$str = preg_replace('#\R+#', '</p><p>', $str);

It was found here: Replacing two new lines with paragraph tags

PHP documentation about Escape sequences:

\R (line break: matches \n, \r and \r\n)


This is the answer, as I understand the question:

// Normalize newlines
preg_replace('/(\r\n|\r|\n)+/', "\n", $text);
// Replace whitespace characters with a single space
preg_replace('/\s+/', ' ', $text);

This is the actual function that I use to convert new lines to HTML line break and paragraph elements:

 * @param string $string
 * @return string
function nl2html($text)
    return '<p>' . preg_replace(array('/(\r\n\r\n|\r\r|\n\n)(\s+)?/', '/\r\n|\r|\n/'),
            array('</p><p>', '<br/>'), $text) . '</p>';


You need the multiline modifier to match multiple lines:

preg_replace("/PATTERN/m", "REPLACE", $text);

Also in your example you seem to be replacing 2+ newlines with exactly 2, which isn’t what your question indicates.


I tried all of above, but it didn’t work for me. Then I created some long way to resolve that issue…

Before :

echo nl2br($text);

After :

$tempData = nl2br($text);
$tempData = explode("<br />",$tempData);

foreach ($tempData as $val) {
   if(trim($val) != '')
      echo $val."<br />";

And it’s worked for me.. I wrote here because, if somebody came here to find answer like me.


I would suggest something like this:

preg_replace("/(\R){2,}/", "$1", $str);

This will take care of all the Unicode newline characters.


If you just want to replace multiple tabs with a single tab, use the following code.

preg_replace("/\s{2,}/", "\t", $string);


Try this:

preg_replace("/[\r\n]*/", "\r\n", $text); 


Replace the head and the end of string or document!



I have dealt with strip_tags function in PHP and had some problems like: after having a linebreak then appear a new line with some spaces and then a new linebreak appear continuously …etc. without any rule :(.

This is my solution for dealing with strip_tags

Replace multiple spaces to one, multiple linebreaks to single linebreak

function cleanHtml($html)
    // Clean code into script tags
    $html = preg_replace('#<script(.*?)>(.*?)</script>#is', '', $html);

    // Clean code into style tags
    $html = preg_replace('/<\s*style.+?<\s*\/\s*style.*?>/si', '', $html );

    // Strip HTML
    $string = trim(strip_tags($html));

    // Replace multiple spaces on each line (keep linebreaks) with single space
    $string = preg_replace("/[[:blank:]]+/", " ", $string); // (*)

    // Replace multiple spaces of all positions (deal with linebreaks) with single linebreak
    $string = preg_replace('/\s{2,}/', "\n", $string); // (**)
    return $string;

Keywords are (*) and (**).