1
我有一個正則表達式:的preg_match不匹配的HTML標記子模式
$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
)
這是爲什麼?爲什麼子模式「(。*)」與'span'不匹配?
'。*'是貪婪的,它儘可能地吃(ᗧ•••)。使用'。*?' – Rizier123
^或'] *>(。*)<\/a>' – splash58
@ splash58這與非貪心,'。*?'基本相同。 –