Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace multiple spaces by non breaking spaces

Tags:

html

regex

php

pcre

How to replace all but first (white)spaces by   when more than one space?

Specifically requested for use with php's preg_replace, so PCRE.

"This is     my text."

Should be converted into

"This is     my text."
like image 784
toshniba Avatar asked Mar 29 '17 09:03

toshniba


1 Answers

It seems all you need is to replace each whitespace that is preceded with another whitespace symbol. Use a lookbehind-based approach:

(?<=\s)\s

See the regex demo.

The (?<=\s) is a positive lookbehind that requires the presence of a whitespace immediately before the current location, but the whitespace is not consumed, and is thus 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.
like image 185
Wiktor Stribiżew Avatar answered Sep 17 '22 17:09

Wiktor Stribiżew