Replace multiple spaces with non-breaking spaces
How do I replace all but the first (white) spaces with
when there is more than one space?
Specifically requested for use with php preg_replace
, so PCRE.
"This is my text."
Needs to be converted to
"This is my text."
It seems that all you need is to replace every space that is preceded by another space character. Use a lookbehind approach:
(?<=\s)\s
See regex demo .
(?<=\s)
is a positive lookbehind that requires a space just before the current location, but the space is not consumed and therefore not replaced.
Below is a PHP demo :
$s = "This is my text.";
echo preg_replace('~(?<=\s)\s~', ' ', $s);
// => This is my text.
More than one space >=2
PHP demo
<?php
echo preg_replace("!\s{2,}!", " ", "Welcome to stack overflow");
Output:
Welcome to stack overflow
What you need to do is use it Regex Lookahead & Lookbehind
like this:
Same:
<?php
echo preg_replace("/\s(?=\s+)|(?<=\s)\s/", " ", "Welcome to stack overflow");
Outputs
Welcome to stack overflow
Test it out here: https://regex101.com/r/DGraSS/1 - gives good explanations :)