Remove multiple whitespaces

PhpRegexStringPreg ReplaceWhitespace

Php Problem Overview


I'm getting $row['message'] from a MySQL database and I need to remove all whitespace like \n \t and so on.

$row['message'] = "This is   a Text \n and so on \t     Text text.";

should be formatted to:

$row['message'] = 'This is a Text and so on Text text.';

I tried:

 $ro = preg_replace('/\s\s+/', ' ',$row['message']);
 echo $ro;

but it doesn't remove \n or \t, just single spaces. Can anyone tell me how to do that?

Php Solutions


Solution 1 - Php

You need:

$ro = preg_replace('/\s+/', ' ', $row['message']);

You are using \s\s+ which means whitespace(space, tab or newline) followed by one or more whitespace. Which effectively means replace two or more whitespace with a single space.

What you want is replace one or more whitespace with single whitespace, so you can use the pattern \s\s* or \s+ (recommended)

Solution 2 - Php

<?php
$str = "This is  a string       with
spaces, tabs and newlines present";

$stripped = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $str);

echo $str;
echo "\n---\n";
echo "$stripped";
?>

This outputs

This is  a string	with
spaces, tabs and newlines present
---
This is a string with spaces, tabs and newlines present

Solution 3 - Php

preg_replace('/[\s]+/mu', ' ', $var);

\s already contains tabs and new lines, so this above regex appears to be sufficient.

Solution 4 - Php

simplified to one function:

function removeWhiteSpace($text)
{
    $text = preg_replace('/[\t\n\r\0\x0B]/', '', $text);
    $text = preg_replace('/([\s])\1+/', ' ', $text);
    $text = trim($text);
    return $text;
}

based on Danuel O'Neal answer.

Solution 5 - Php

$str='This is   a Text \n and so on Text text.';
print preg_replace("/[[:blank:]]+/"," ",$str);

Solution 6 - Php

I can't replicate the problem here:

$x = "this    \n \t\t \n    works.";
var_dump(preg_replace('/\s\s+/', ' ', $x));
// string(11) "this works."

I'm not sure if it was just a transcription error or not, but in your example, you're using a single-quoted string. \n and \t are only treated as new-line and tab if you've got a double quoted string. That is:

'\n\t' != "\n\t"

Edit: as Codaddict pointed out, \s\s+ won't replace a single tab character. I still don't think using \s+ is an efficient solution though, so how about this instead:

preg_replace('/(?:\s\s+|\n|\t)/', ' ', $x);

Solution 7 - Php

preg_replace('/(\s\s+|\t|\n)/', ' ', $row['message']);

This replaces all tabs, all newlines and all combinations of multiple spaces, tabs and newlines with a single space.

Solution 8 - Php

<?php
#This should help some newbies
# REGEX NOTES FROM DANUEL
# I wrote these functions for my own php framework
# Feel Free to make it better
# If it gets more complicated than this. You need to do more software engineering/logic.
# (.)  // capture any character
# \1   // if it is followed by itself
# +    // one or more

class whitespace{

    static function remove_doublewhitespace($s = null){
           return  $ret = preg_replace('/([\s])\1+/', ' ', $s);
    }

    static function remove_whitespace($s = null){
           return $ret = preg_replace('/[\s]+/', '', $s );
    }

    static function remove_whitespace_feed( $s = null){
           return $ret = preg_replace('/[\t\n\r\0\x0B]/', '', $s);
    }

    static function smart_clean($s = null){
           return $ret = trim( self::remove_doublewhitespace( self::remove_whitespace_feed($s) ) );
    }
}
$string = " Hey   yo, what's \t\n\tthe sc\r\nen\n\tario! \n";
echo whitespace::smart_clean($string);

Solution 9 - Php

Without preg_replace()

$str = "This is   a Text \n and so on \t     Text text.";
$str = str_replace(["\r", "\n", "\t"], " ", $str);
while (strpos($str, "  ") !== false)
{
    $str = str_replace("  ", " ", $str);
}
echo $str;

Solution 10 - Php

This is what I would use:

a. Make sure to use double quotes, for example:

$row['message'] = "This is   a Text \n and so on \t     Text text.";

b. To remove extra whitespace, use:

$ro = preg_replace('/\s+/', ' ', $row['message']); 
echo $ro;

It may not be the fastest solution, but I think it will require the least code, and it should work. I've never used mysql, though, so I may be wrong.

Solution 11 - Php

All you need is to run it as follows:

echo preg_replace('/\s{2,}/', ' ', "This is   a Text \n and so on \t     Text text."); // This is a Text and so on Text text.

Solution 12 - Php

I use this code and pattern:

preg_replace('/\\s+/', ' ',$data)

$data = 'This is   a Text 
   and so on         Text text on multiple lines and with        whitespaces';
$data= preg_replace('/\\s+/', ' ',$data);
echo $data;

You may test this on http://writecodeonline.com/php/

Solution 13 - Php

On the truth, if think that you want something like this:

preg_replace('/\n+|\t+|\s+/',' ',$string);

Solution 14 - Php

this will replace multiple tabs with a single tab

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

Solution 15 - Php

Without preg_replace, with the help of loop.

<?php

$str = "This is   a Text \n and so on \t     Text text.";
$str_length = strlen($str);
$str_arr = str_split($str);
for ($i = 0; $i < $str_length; $i++) {
    if (isset($str_arr[$i + 1])
       && $str_arr[$i] == ' '
       && $str_arr[$i] == $str_arr[$i + 1]) {
       unset($str_arr[$i]);
    } 
    else {
      continue;
    }
}

 echo implode("", $str_arr) ; 

 ?>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncreativzView Question on Stackoverflow
Solution 1 - PhpcodaddictView Answer on Stackoverflow
Solution 2 - PhpcEzView Answer on Stackoverflow
Solution 3 - PhpAnonymousView Answer on Stackoverflow
Solution 4 - PhpLukas LiesisView Answer on Stackoverflow
Solution 5 - Phpghostdog74View Answer on Stackoverflow
Solution 6 - PhpnickfView Answer on Stackoverflow
Solution 7 - PhpmiddusView Answer on Stackoverflow
Solution 8 - PhpDanuel O'NealView Answer on Stackoverflow
Solution 9 - PhphharekView Answer on Stackoverflow
Solution 10 - PhpmatsolofView Answer on Stackoverflow
Solution 11 - PhpAlex PoloView Answer on Stackoverflow
Solution 12 - PhpCatalin T.View Answer on Stackoverflow
Solution 13 - PhpBigBlastView Answer on Stackoverflow
Solution 14 - PhpHeman GView Answer on Stackoverflow
Solution 15 - PhpShahbaz KhanView Answer on Stackoverflow