Remove multiple whitespaces

creativz picture creativz · Feb 24, 2010 · Viewed 230.7k times · Source

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?

Answer

codaddict picture codaddict · Feb 24, 2010

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)