在 PHP 中,如何完成仅返回分组内容的正则表达式
我想使用分组执行正则表达式。我只对分组感兴趣,这是我想要的全部返回。这可能吗?
$haystack = '<a href="/foo.php">Go To Foo</a>';
$needle = '/href="(.*)">/';
preg_match($needle,$haystack,$matches);
print_r($matches);
//Outputs
//Array ( [0] => href="/foo.php"> [1] => /foo.php )
//I want:
//Array ( [0] => /foo.php )
I want to perform a regex using grouping. I am only interested in the grouping, its all I want returned. Is this possible?
$haystack = '<a href="/foo.php">Go To Foo</a>';
$needle = '/href="(.*)">/';
preg_match($needle,$haystack,$matches);
print_r($matches);
//Outputs
//Array ( [0] => href="/foo.php"> [1] => /foo.php )
//I want:
//Array ( [0] => /foo.php )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实际上,通过环视这是可能的。而不是:
现在
,这将匹配(并因此捕获到组 0)任何前面为
href="
且后面为"> 的
。请注意,我高度怀疑您确实需要.*
。.*?
相反,即不情愿而不是贪婪。无论如何,PHP 的
preg
看起来像是 PCRE,所以它应该支持环视。正则表达式.info 链接
preg
函数实现了 PCRE 风格。(?=regex)
(正向前瞻):是(?<=text)
(正向后查找):固定 + 交替演示
在 ideone.com 上运行此代码 会产生:
相关问题
这些大多是 Java,但正则表达式部分涵盖了使用lookarounds/assertions:
Actually this is possible with lookarounds. Instead of:
You want
Now this will match (and therefore capture into group 0) any
.*
that is preceded byhref="
and followed by">
. Note that I highly suspect that you really need.*?
instead, i.e. reluctant instead of greedy.In any case, it looks like PHP's
preg
is PCRE, so it should support lookarounds.regular-expressions.info links
preg
functions implement the PCRE flavor.(?=regex)
(positive lookahead): YES(?<=text)
(positive lookbehind): fixed + alternationDemonstration
Running this on ideone.com produces:
Related questions
These are mostly Java, but the regex part covers using lookarounds/assertions:
不。0 索引将始终是匹配的文本,而不是组。当然,您可以只删除第一个元素并重新对数组进行编号。
No. The 0 index will always be the text that was matches, not the groups. Of course, you can just remove the first element and renumber the array.
您可以使用
array_shift()
:但没有标志告诉
preg_match
做你想做的事情。无论如何,正如您所知,它将始终存在,您应该能够在代码中处理这个问题。
你为什么想要/需要这个?
You could use
array_shift()
:but there is no flag to tell
preg_match
to do what you want.Anyway, as you know that it will always be there, you should be able to handle this in your code.
Why do you want / need this?