Replacing spaces with regex in PHP

I am new to regular expressions. I have a requirement to replace spaces in a piece of multi-line text. Replacement Rules:

  • Replace all spaces at the beginning of the line with non-breaking space (  ).
  • Replace any instance of repeating spaces (more than one space together) with the same number of non-breaking spaces.
  • Individual spaces that are not at the beginning of a line remain untouched.

I used Regex Coach to create the appropriate template:

/( ){2,}|^( )/

Suppose I have this input:

asdasd asdasd  asdas1
 asda234 4545    54
  34545 345  34534
34 345

Using the PHP regular expression replacement function (e.g. preg_replace()), I want to get this output:

asdasd asdasd  asdas1
 asda234 4545    54
  34545 345  34534
34 345

, , , , .

+3
2

, . "look-ahead" "look-behind".

(\x20), , - (\s); .

$str = "asdasd asdasd  asdas1\n asda234 4545    54\n  34545 345  34534\n34 345\n";

print preg_replace("/(?<=\s)\x20|\x20(?=\s)/", "&#160;", $str);

( # 160, nbsp.)

:

asdasd asdasd&#160;&#160;asdas1
&#160;asda234 4545&#160;&#160;&#160;&#160;54
&#160;&#160;34545 345&#160;&#160;34534
34 345

PCRE perlre.


@ Sprogz: . a "\n " => "\n&nbsp;" 1- 2- .

+6

PHP /e , :

$str = preg_replace('/( {2,}|^ )/em', 'str_repeat("&nbsp;", strlen("\1"))', $str);

, . /m , ^ .

+2

Source: https://habr.com/ru/post/1698339/


All Articles