Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php Replacing multiple spaces with a single space [duplicate]

People also ask

How do I replace multiple spaces in single space?

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.

How do you replace 2 or more spaces with single space in the string and delete leading spaces only?

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

How can I replace multiple characters in a string in PHP?

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)