【问题标题】:preg_match not matching subpattern with html tagpreg_match 不匹配带有 html 标记的子模式
【发布时间】: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'?

【问题讨论】:

  • .* 是贪婪的,它会吃尽可能多的东西 (ᗧ•••)。使用.*?
  • ^ 或 &lt;a class="title"[^&gt;]*&gt;(.*)&lt;\/a&gt;
  • @splash58 与非贪婪基本相同,.*?
  • @Sverri M. Olsen 我明白了,只是我写了评论并决定不清除它

标签: php regex html-parsing preg-match


【解决方案1】:

将你的模式更改为

$reg = '/<a class="title"[^>]*>([^<]*)<\/a>/';

这样它就知道你想要什么,除非第一部分是 &lt; 或第二部分是 &gt;

<a class="title"[^>]*> //Get the opening tag
([^<]*) //match anything until you reach a closing tag
<\/a> // your closing tag

【讨论】:

    猜你喜欢
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 2012-02-16
    • 1970-01-01
    相关资源
    最近更新 更多