How the pattern works
| Part | Meaning |
|---|---|
[ \t] | A space or tab |
{2,} | Two or more in a row |
→ " " | Replaced with a single space |
Code examples
JavaScript
const out = text.replace(/[ \t]{2,}/g, " ");Python
import re
out = re.sub(r'[ \t]{2,}', r' ', text)PHP
$out = preg_replace('/[ \t]{2,}/', ' ', $text);
Notes and limitations
Use \s{2,} instead to also collapse line breaks into spaces. The Remove Extra Spaces tool does both.
Regex TesterType a pattern and watch matches highlight live in your test text.
Open the tool Frequently asked questions
What is the regex to collapse multiple spaces?
/[ \t]{2,}/g — it is used with find and replace. See the table above for what each part does.
Does it work in Python and PHP?
Yes — the code examples above use the same pattern with re in Python and preg functions in PHP.
How do I test this regex?
Click “Open in Regex Tester” — the pattern, flags and sample text load automatically, and matches highlight as you edit.