Regular Expression: Remove Duplicate Spaces
Question by SimplyMe | Last update on 2022-12-09 | Created on 2012-12-25
I'm looking for a regular expression to remove all double spaces from a string. I know that I can use the function trim() in order to remove unnecessary blanks from the beginning and the end of a string. But how can I do this also for the middle of the string?
Related Topics
PHP: Remove arbitrary Characters at the Beginning and the End of a String
Tutorial | 0 Comments
How to Replace multiple Texts at the same Time
Tutorial | 0 Comments
PHP: Check Strings with Ctype-Functions for Character Classes
Article | 0 Comments
HTML: No line break between particular words
Tip | 0 Comments
HTACCESS: Simplify URL
Tutorial | 0 Comments
JavaScript: Remove leading zeros
Tip | 2 Comments
Important Note
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Participate
Ask your own question or write your own article on askingbox.com. That’s how it’s done.
The regular expression to match double spaces is " +" - a space followed by a plus sign that stands for an arbitrary repetition.
If we search for that and replace all occurrences with a single space, we can remove all double spaces from a text respectively string. Here is an example for PHP:
Remove double Whitespace
Since you also spoke about the trim function that removes all types of whitespace, here is another example of how you can not only remove the double spaces but also any other double whitespace such as spaces, tabs, line breaks and so on:
The \s stands for any whitespace character, so it matches spaces, tabs, line breaks and so on. With the plus we are now looking for all events in our string $s, where at least two whitespace characters occur in a row. We then replace every hit with a single space.
Last update on 2022-12-09 | Created on 2012-12-26