为什么preg_replace提供此输出?

时间:2010-08-17 02:34:53

标签: php regex preg-replace

由于某种原因,我无法解决这个问题:

$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;

输出这个(下面),我无法理解为什么它根据我设置的方式替换“width:”..任何建议表示赞赏

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

1 个答案:

答案 0 :(得分:5)

问题是您的替换字符串如下所示:

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

因为紧跟在组号后面的字符是一个数字,所以它被解释为第48组而不是第4组。

参见preg_replace手册“示例#1使用反向引用后跟数字文字”。使其工作所需的最小变化是用花括号围绕4,以便它与88分开。

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

但这不是一个很好的方法,你的代码也存在许多问题。

  • 正则表达式不适合解析和修改CSS。
  • 首先编写$elementwidth,然后编写$element_width
  • 如果您只打算替换其中一个,则无需创建6个不同的组。