2

I'm looking to replace multiple instances of space characters. My initial searches all seem to focus on using the /s but this includes newlines and other whitespace

I think this should be close? replace two or more instances spaces " " with one space

preg_replace('/ {2,}/', ' ', $string);
3
  • Looks fine as it is. What's the problem? Commented Apr 2, 2012 at 10:49
  • 1
    What is your question? The regex looks good! Commented Apr 2, 2012 at 10:49
  • really? Must have been a good guess. Been trying to find it for ages Commented Apr 2, 2012 at 10:55

2 Answers 2

4

What about trying this :

preg_replace('/\s\s+/', ' ', $string);
Sign up to request clarification or add additional context in comments.

3 Comments

The OP doesn't want \s, because it does include not only spaces.
what does the [] brackets do. is it to help split up pattern so its easier to read?
@Robbo_UK Well, by using brackets, you search for ANY of the elements WITHIN the brackets... So, e.g. [abc] means "search for one of the three characters : a,b OR c. In your case, it includes just one character : space. So, basically to explain my regex, it reads : "Search for one space. Then, search for AT LEAST one (more)space." ==> In other words, for AT LEAST 2 spaces (one after the other)... :-)
2
$str = <<<EOT
word  word   123.

new line  word


new line  word
EOT;

$replaced = preg_replace('#\h{2,}#', ' ', $str);

var_dump($replaced);

output:

word word 123.

new line word


new line word

\h matches any horizontal whitespace character (equivalent to [[:blank:]])
{2,} matches the previous token between 2 and unlimited times, as many times as possible, giving back as needed (greedy)

Credits: https://regex101.com/

Use \v for vertical whitespace, \s for any whitespace.

1 Comment

The m flag is useless for this pattern because the pattern contains no start or end anchors (^ or $). This answer is misleading researchers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.