【发布时间】:2015-10-09 22:54:14
【问题描述】:
我有一个正则表达式:
$reg = '/<a class="title".*>(.*)<\/a>/';
以及以下文字:
$text = '<h3 class="carousel-post-title"><a class="title" href="/first-link/">Some text<br /><span class="title-highlight">with a span</span></a></h3>'
我传递给 preg_match:
$matches = [];
preg_match($reg, $text, $matches);
返回
Array (
[0] => <a class="title" href="/first-link/">Some text<br /><span class="title-highlight">with a span</span></a>
[1] =>
)
而
$text2 = '<h3 class="carousel-post-title"><a class="title" href="/second-link/">Some text here</a></h3>';
preg_match($reg, $text2, $matches);
返回
Array
(
[0] => <a class="title" href="/second-link/">Some text here</a>
[1] => Some text here
)
这是为什么呢?为什么子模式“(.*)”不匹配'with a span'?
【问题讨论】:
-
.*是贪婪的,它会吃尽可能多的东西 (ᗧ•••)。使用.*? -
^ 或
<a class="title"[^>]*>(.*)<\/a> -
@splash58 与非贪婪基本相同,
.*?。 -
@Sverri M. Olsen 我明白了,只是我写了评论并决定不清除它
标签: php regex html-parsing preg-match