The metacharacter “\s” matches spaces and + indicates the occurrence of the spaces one or more times, therefore, the regular expression \S+ matches all the space characters (single or multiple). Therefore, to replace multiple spaces with a single space.
You just need a: replaceAll("\\s{2,}", " "). trim(); where you match one or more spaces and replace them with a single space and then trim whitespaces at the beginning and end (you could actually invert by first trimming and then matching to make the regex quicker as someone pointed out).
Approach 1: Using the str_replace() and str_split() functions in PHP. The str_replace() function is used to replace multiple characters in a string and it takes in three parameters. The first parameter is the array of characters to replace.
Use preg_replace()
and instead of [ \t\n\r]
use \s
:
$output = preg_replace('!\s+!', ' ', $input);
From Regular Expression Basic Syntax Reference:
\d, \w and \s
Shorthand character classes matching digits, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks). Can be used inside and outside character classes.
$output = preg_replace('/\s+/', ' ',$input);
\s is shorthand for [ \t\n\r]
. Multiple spaces will be replaced with single space.
preg_replace("/[[:blank:]]+/"," ",$input)
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