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);
Robbo_UK
  • 11,351
  • 25
  • 81
  • 117

2 Answers2

4

What about trying this :

preg_replace('/\s\s+/', ' ', $string);
Dr.Kameleon
  • 22,532
  • 20
  • 115
  • 223
  • 1
    The OP doesn't want `\s`, because it does include not only spaces. – stema Apr 02 '12 at 10:53
  • what does the `[]` brackets do. is it to help split up pattern so its easier to read? – Robbo_UK Apr 02 '12 at 12:28
  • 1
    @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)... :-) – Dr.Kameleon Apr 02 '12 at 19:35
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.

vee
  • 4,506
  • 5
  • 44
  • 81
  • The `m` flag is useless for this pattern because the pattern contains no start or end anchors (`^` or `$`). This answer is misleading researchers. – mickmackusa Jun 10 '22 at 23:55