Ric*_*ick 3 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;
Run Code Online (Sandbox Code Playgroud)
输出这个(下面),我无法理解为什么它取代了"宽度:"基于我设置它的方式..任何建议表示赞赏
#mainparent { position: relative; top: 100px; left: 100px; 88; }
Run Code Online (Sandbox Code Playgroud)
问题是您的替换字符串如下所示:
'$1$2$3$488$6'
^^^
Run Code Online (Sandbox Code Playgroud)
因为紧跟在组编号之后的字符是数字,所以它被解释为组48而不是组4.
请参阅preg_replace手册"示例#1使用反向引用后跟数字文字".使其工作所需的最小变化是用花括号围绕4,以便它与88分开.
$replacement = '$1' . '$2' . '$3'. '${4}'. $element_width . '$6';
Run Code Online (Sandbox Code Playgroud)
但这不是一个很好的方法,你的代码也存在许多问题.
$elementwidth,然后你写$element_width.