贪婪量词匹配两个连续的段,而不是进行两个单独的匹配
这是我正在使用的代码;
$string = "[if-protectDelete-{0}-][data]name[/data] can be deleted[/elseif][elseif-{1}-][data]name[/data] can't be deleted[/elseif][elseif-{2}-]No data[/elseif][/endif]";
if (preg_match_all("#\[elseif-\{(.+)\}-\](.+?)\[/elseif\]#", $string, $matches)) {
dumper($matches[0]);
}
$matches[0] 输出为;
array(1) {
[0]=> string(75) "[elseif-{1}-]PHP REGEX can't be deleted[/elseif][elseif-{2}-]No data[/elseif]"
}
我可以得到正确的 if 部分,但是 elseif...我想这是完全不同的场景。 不应该这样输出吗?
array {
[0] => "[elseif-{1}-]PHP REGEX can't be deleted[/elseif]",
[1] => "[elseif-{2}-]No data[/elseif]"
}
Here is the code I'm using;
$string = "[if-protectDelete-{0}-][data]name[/data] can be deleted[/elseif][elseif-{1}-][data]name[/data] can't be deleted[/elseif][elseif-{2}-]No data[/elseif][/endif]";
if (preg_match_all("#\[elseif-\{(.+)\}-\](.+?)\[/elseif\]#", $string, $matches)) {
dumper($matches[0]);
}
$matches[0] output is;
array(1) {
[0]=> string(75) "[elseif-{1}-]PHP REGEX can't be deleted[/elseif][elseif-{2}-]No data[/elseif]"
}
I can get the part right for if, but elseif... It is totally different scenario I guess.
Shouldn't it output like this?
array {
[0] => "[elseif-{1}-]PHP REGEX can't be deleted[/elseif]",
[1] => "[elseif-{2}-]No data[/elseif]"
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需添加?
Just add ?
我不知道
dumper
做什么,但数组$matches
包含$matches[0]
中的整个匹配以及$matches[0]
中捕获的组code>$matches[1]$matches[2]
...所以你应该这样做:
print_r($matches);
来获取你的匹配组。I don't know what
dumper
do but the array$matches
contains the whole matching in$matches[0]
and the groups captured in$matches[1]
$matches[2]
...so you should do :
print_r($matches);
to get your matches groups.看起来你仍然有一个贪婪的
+
。这可能会解决这个问题:注意
[0-9]+
替换了.+
。让我知道进展如何。假设大括号内可能有任何内容,除了其他大括号之外,这会更好:
或者,就像您提到的:
.+?
It looks like you still have a greedy
+
in there. This might fix it:Notice the
[0-9]+
that replaces the.+
. Let me know how that goes.Assuming you might have anything inside the curly braces, except other curly breaces, this would be even better:
Or, like you mentioned:
.+?