Preg 匹配除字符串之外的所有贪婪匹配
我的源字符串是这样的:
{categories group_id="3"}
{category_name}
{/categories}
{categories group_id="4"}
{category_name}
{/categories}
我的正则表达式是这样的:
preg_match('/{categories group_id="3"}(.*){\/categories}/s', $tagdata, $matches);
结果是:
Array
(
[0] => Array
(
[0] => {categories group_id="3"}
{category_name}
{/categories}
{categories group_id="4"}
{category_name}
{/categories}
)
[1] => Array
(
[0] =>
{category_name}
{/categories}
{categories group_id="4"}
{category_name}
)
)
你可以看到贪婪太贪婪了,它一直到第二个实例的末尾。我期待的是这样的:
Array
(
[0] => Array
(
[0] => {categories group_id="3"}
{category_name}
{/categories}
)
[1] => Array
(
[0] =>
{category_name}
)
)
My source string is this:
{categories group_id="3"}
{category_name}
{/categories}
{categories group_id="4"}
{category_name}
{/categories}
My regex is this:
preg_match('/{categories group_id="3"}(.*){\/categories}/s', $tagdata, $matches);
Which results in:
Array
(
[0] => Array
(
[0] => {categories group_id="3"}
{category_name}
{/categories}
{categories group_id="4"}
{category_name}
{/categories}
)
[1] => Array
(
[0] =>
{category_name}
{/categories}
{categories group_id="4"}
{category_name}
)
)
You can see that the greediness is too greedy, and it goes all the way to the end of the second instance. What I'm expecting is this:
Array
(
[0] => Array
(
[0] => {categories group_id="3"}
{category_name}
{/categories}
)
[1] => Array
(
[0] =>
{category_name}
)
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
同意@user779
另一种方法是在正则表达式末尾添加一个 U (PCRE_UNGREEDY) 修饰符,这使所有量词变得懒惰。
更多信息在这里: http://php.net/manual/en/reference .pcre.pattern.modifiers.php
Agree with @user779
Also another way is to add a U (PCRE_UNGREEDY) modifier at the end of your regexp which makes all quantifiers lazy.
More info here: http://php.net/manual/en/reference.pcre.pattern.modifiers.php