I’m pretty new to regular expressions. I have a requirement to replace spaces in a piece of multi-line text. The replacement rules are these:
- Replace all spaces at start-of-line with a non-breaking space (
). - Replace any instance of repeated spaces (more than one space together) with the same number of non-breaking-spaces.
- Single spaces which are not at start-of-line remain untouched.
I used the Regex Coach to build the matching pattern:
/( ){2,}|^( )/
Let’s assume I have this input text:
asdasd asdasd asdas1 asda234 4545 54 34545 345 34534 34 345
Using a PHP regular expression replace function (like preg_replace()), I want to get this output:
asdasd asdasd  asdas1  asda234 4545    54   34545 345  34534 34 345
I’m happy doing simple text substitutions using regular expressions, but I’m having trouble working out how to replace multiple-times inside the match in order to get the output I desire.
I’d guess that it would be easier to find each space and replace it. To do that, use "look-ahead" and "look-behind" groups.
Or, find a space (
\x20) that is either lead by or followed by any single whitespace (\s); but, only replace the space.(I opted for #160 since markdown parses nbsp.)
Results in:
For more info, check out PCRE and perlre.
reply to comments
@Sprogz: At first, I thought the same. But the example shows a
"\n " => "\n "between the 1st and 2nd lines.