24 Votes

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?

ReplyPositiveNegative
4Best Answer6 Votes

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:

$s = 'A   Sentence.';
$s = preg_replace('# +#', ' ', $s);
echo $s; // 'A Sentence.'

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:

$s = 'A   Sentence.';
$s = preg_replace('#\s+#', ' ', $s);
echo $s; // 'A Sentence.'

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

ReplyPositive Negative
Reply

Related Topics

HTACCESS: Simplify URL

Tutorial | 0 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.