Why does preg_replace give this result?

I just can't figure it out, for some reason this:

$string = "#mainparent {
position: relative;
top: 100px;
left: 100px;
width:4994px;
}";

$elementwidth = "88";

  $re1='(.*?)'; # Non-greedy match on filler
  $re2='(mainparent)';  # Word 1
  $re3='(.*)';  # Non-greedy match on filler
  $re4='(width:)';
  $re5='(.*)';  # Word 2
  $re6='(;)';   # Any Single Character 1
$pattern="/".$re1.$re2.$re3.$re4.$re5.$re6."/s";
    $replacement= '$1'.'$2'.'$3'. '$4'. $element_width .'$6';
    $return_string = preg_replace_component ($string, $pattern, $replacement );
     #c}

     echo $return_string; return;

output this (below), I can’t understand why it replaces “width:” based on how I configured it .. any tips are welcome

#mainparent { position: relative; top: 100px; left: 100px; 88; } 
+3
source share
1 answer

The problem is that your replacement string looks like this:

'$1$2$3$488$6'
       ^^^

Since the character following the group number is a number, it is interpreted as group 48 instead of group 4.

. preg_replace " # 1 , ". , , , 4 , 88.

$replacement = '$1' . '$2' . '$3'. '${4}'. $element_width . '$6';

, .

  • CSS.
  • $elementwidth, $element_width.
  • 6 , .
+5

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


All Articles