Remove multiple whitespaces Remove multiple whitespaces php php

Remove multiple whitespaces


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)


<?php$str = "This is  a string       withspaces, 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   withspaces, tabs and newlines present---This is a string with spaces, tabs and newlines present


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

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