Home » Php » Replace excess whitespaces and line-breaks with PHP?

Replace excess whitespaces and line-breaks with PHP?

Posted by: admin November 29, 2017 Leave a comment

Questions:
$string = "My    text       has so    much   whitespace    




Plenty of    spaces  and            tabs";

echo preg_replace("/\s\s+/", " ", $string);

I read the PHP’s documentation and follow the preg_replace’s tutorial, however this code produce

My text has so much whitespace Plenty of spaces and tabs

How can I turn it into :

My text has so much whitespace
Plenty of spaces and tabs

Answers:

First, I’d like to point out that new lines can be either \r, \n, or \r\n depending on the operating system.

My solution:

echo preg_replace('/[ \t]+/', ' ', preg_replace('/[\r\n]+/', "\n", $string));

Which could be separated into 2 lines if necessary:

$string = preg_replace('/[\r\n]+/', "\n", $string);
echo preg_replace('/[ \t]+/', ' ', $string);

Update:

An even better solutions would be this one:

echo preg_replace('/[ \t]+/', ' ', preg_replace('/\s*$^\s*/m', "\n", $string));

Or:

$string = preg_replace('/\s*$^\s*/m', "\n", $string);
echo preg_replace('/[ \t]+/', ' ', $string);

I’ve changed the regular expression that makes multiple lines breaks into a single better. It uses the “m” modifier (which makes ^ and $ match the start and end of new lines) and removes any \s (space, tab, new line, line break) characters that are a the end of a string and the beginning of the next. This solve the problem of empty lines that have nothing but spaces. With my previous example, if a line was filled with spaces, it would have skipped an extra line.

Questions:
Answers:

Edited the right answer. From PHP 5.2.4 or so, the following code will do:

echo preg_replace('/\v(?:[\v\h]+)/', '', $string);

Questions:
Answers:

Replace Multiple Newline, Tab, Space

$text = preg_replace("/[\r\n]+/", "\n", $text);
$text = preg_replace("/\s+/", ' ', $text);

Tested 🙂

Questions:
Answers:

Alternative approach:

echo preg_replace_callback("/\s+/", function ($match) {
    $result = array();
    $prev = null;
    foreach (str_split($match[0], 1) as $char) {
        if ($prev === null || $char != $prev) {
            $result[] = $char;
        }

        $prev = $char;
    }

    return implode('', $result);
}, $string);

Output:

My text has so much whitespace
Plenty of spaces and tabs

Edit: Readded this for it being a different approach. It’s probably not what’s asked for, but it will at least not merge groups of different whitespace (e.g. space, tab, tab, space, nl, nl, space, space would become space, tab, space, nl, space).

Questions:
Answers:
//Newline and tab space to single space

$from_mysql = str_replace(array("\r\n", "\r", "\n", "\t"), ' ', $from_mysql);


// Multiple spaces to single space ( using regular expression)

$from_mysql = ereg_replace(" {2,}", ' ',$from_mysql);

// Replaces 2 or more spaces with a single space, {2,} indicates that you are looking for 2 or more than 2 spaces in a string.

Questions:
Answers:

why you are doing like this?
html displays only one space even you use more than one space…

For example:

<i>test               content 1       2 3 4            5</i>

The output willl be:
test content 1 2 3 4 5

if you need more than single space in html, you have to use &nbsp;

Questions:
Answers:

try with:

$string = "My    text       has so    much   whitespace    




Plenty of    spaces  and            tabs";
//Remove duplicate newlines
$string = preg_replace("/[\n]*/", "\n", $string); 
//Preserves newlines while replacing the other whitspaces with single space
echo preg_replace("/[ \t]*/", " ", $string); 

Questions:
Answers:

this would COMPLETELY MINIFY the entire string (such as a large blog article) yet preserving all HTML tags in place.

$email_body = str_replace(PHP_EOL, ' ', $email_body);
    //PHP_EOL = PHP_End_Of_Line - would remove new lines too
$email_body = preg_replace('/[\r\n]+/', "\n", $email_body);
$email_body = preg_replace('/[ \t]+/', ' ', $email_body);