Using sting split() and join() You can also use the string split() and join() functions to remove multiple spaces from a string. We get the same result as above. Note that the string split() function splits the string at whitespace characters by default.
The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".
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 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
preg_replace('/[\s]+/mu', ' ', $var);
\s
already contains tabs and new lines, so this above regex appears to be sufficient.
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.
$str='This is a Text \n and so on Text text.';
print preg_replace("/[[:blank:]]+/"," ",$str);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With