开发者

Why is preg_replace giving this output?

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

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

$elementwidth = "88";

  $re1='(开发者_C百科.*?)'; # 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 is replacing the "width:" based on the way I have set it up.. any advice is appreciated

#mainparent { position: relative; top: 100px; left: 100px; 88; } 


The problem is that your replacement string looks like this:

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

Because the character immediately following the group number is a digit, it is being interpreted as group 48 instead of group 4.

See the preg_replace manual "Example #1 Using backreferences followed by numeric literals". The smallest change required to make it work is to surround the 4 by curly braces so that it is separated from the 88.

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

But this isn't a good way to do it and there are also a number of issues with your code.

  • Regular expressions are not really suitable for parsing and modifying CSS.
  • First you write $elementwidth and later you write $element_width.
  • It's not necessary to create 6 different groups if you only intend to replace one of them.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜