255

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?

2
  • 2
    The newline and tab characters are in single quotes, so you want them literal?
    – Mark Lalor
    Aug 23, 2010 at 20:01
  • I fixed the quoting of the code sectin with the \n and \t by changing it to double-quotes. Sep 13, 2013 at 7:51

15 Answers 15

464

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)

12
  • 2
    his method is better than this: why would you replace one space with one space?
    – nickf
    Feb 24, 2010 at 13:13
  • 19
    He also wants \n and \t to be replaced with space. Now his pattern does not match these, say for $x = "does\nthis\twork"; The OP wants all whitespace to be replaced with a single space.
    – codaddict
    Feb 24, 2010 at 13:17
  • 1
    @codaddict, how we can keep \n and remove all other multiple space and tabs from the string? please help me Sep 20, 2013 at 9:20
  • 1
    Can you be more specific why "\s+" is recommended?
    – Isius
    Oct 25, 2013 at 3:09
  • 8
    Note that in PHP \s not including "vertical tab" chr(11). To include it too you need to use space character class: [[:space:]]+ php.net/manual/en/regexp.reference.character-classes.php
    – Yaroslav
    Oct 29, 2013 at 18:49
79
<?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
0
18
preg_replace('/[\s]+/mu', ' ', $var);

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

1
  • 2
    Square brackets aren't needed here because there's only one thing inside them. The /m wont have an effect as there are no ^ or $ anchors and the /u won't have any effect except to slow it down slightly and die if the input string is not valid UTF-8 (it doesn't affect what \s matches, but it would affect \pZ). May 17, 2016 at 4:18
15

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.

10
$str='This is   a Text \n and so on Text text.';
print preg_replace("/[[:blank:]]+/"," ",$str);
2
  • 3
    This is the one that worked for me the best. Also, I would add trim to erase whitespace in the beginning and end of string
    – Dziamid
    Jun 1, 2012 at 10:20
  • 1
    @Dziamid You can do it with trim(preg_replace(...)) Dec 11, 2014 at 12:20
10

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);
3
  • 3
    +1, True. For a string with plenty of single spaces (which usually is the case) it is inefficient to replace a space with space.
    – codaddict
    Feb 24, 2010 at 13:32
  • 2
    @coaddict: to test your hypothesis, i wrote a quick script to run through 1000 of each replacement and check the timing of each. For the string '+1, True. For a string with plenty of single spaces (which usually is the case) it is inefficient to replace a space with space. – codaddict Feb 24 \'10 at 13:32', one thousand \s+ preg_replace() calls took 0.010547876358032 seconds, and one thousand (?:\s\s+|\n|\t) preg_replace() calls took 0.013049125671387, making it almost 30% slower. May 1, 2014 at 23:31
  • You may want to add "\r" to that last example as some computers do use a single "\r" on its own (Apple Mac?) May 17, 2016 at 4:26
6
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.

2
  • \t & \n are already included in \s so your regex is exactly the same than \s\s+ that is better written \s{2,} just like @Alex Polo answer
    – Toto
    Mar 8, 2021 at 12:41
  • I needed the same functionality as in the original question only without replacing the single space with single space character and this is the solution
    – 6opko
    Oct 11, 2022 at 13:48
4
<?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);
2
  • 3
    static function remove_whitespace is for what reason? You define but never use it. May 29, 2015 at 11:37
  • 1
    These each have their use but none of these would achieve what the question asks for which is to replace multiple consecutive whitespace with just one. Your "remove_doublewhitespace" would only replace multiple of the same whitespace character, so it would replace "\n\n\n" with a ' ', but it would not do anything to " \r\n" May 17, 2016 at 4:22
4

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

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.

2

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.
2

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/

1
  • 1
    It works with me even in mariaDB in this query: SELECT search_able, REGEXP_REPLACE (search_able,"\\s+",' ') FROM book where id =260 So Thanks a lot
    – jalmatari
    Sep 28, 2019 at 18:17
1

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

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

this will replace multiple tabs with a single tab

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

Without preg_replace, with the help of loop.

<?php

$str = "This is   a Text  and so on      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) ; 

 ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.