Replace multiple spaces with non-breaking spaces
3 answers
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.
+2
source to share
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 :)
0
source to share