为什么 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;
输出这个(如下),我不明白为什么它根据我设置的方式替换“宽度:”..任何建议表示赞赏
#mainparent { position: relative; top: 100px; left: 100px; 88; }
I just can't figure this 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 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; }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是您的替换字符串如下所示:
由于紧跟在组编号后面的字符是数字,因此它被解释为组 48 而不是组 4。
请参阅 preg_replace 手册“示例#1 使用反向引用后跟数字文字”。使其工作所需的最小更改是用大括号将 4 括起来,以便将其与 88 分开。
但这不是一个好方法,而且您的代码也存在许多问题。
$elementwidth
,然后编写$element_width
。The problem is that your replacement string looks like this:
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.
But this isn't a good way to do it and there are also a number of issues with your code.
$elementwidth
and later you write$element_width
.