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."

      

+3


source to share


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~', '&nbsp;', $s);
// => This is &nbsp;&nbsp;&nbsp;&nbsp;my text.

      

+2


source


More than one space >=2

PHP demo

<?php

echo preg_replace("!\s{2,}!", " &nbsp;", "Welcome to stack  overflow");

      



Output:

Welcome to stack &nbsp;overflow

      

+1


source


What you need to do is use it Regex Lookahead & Lookbehind

like this:

Same:

<?php
echo preg_replace("/\s(?=\s+)|(?<=\s)\s/", "&nbsp;", "Welcome to stack       overflow");

      

Outputs

Welcome to stack&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;overflow

      

Test it out here: https://regex101.com/r/DGraSS/1 - gives good explanations :)

0


source







All Articles