【问题标题】:How to fetch all anchor tag text from div using regexp如何使用正则表达式从 div 中获取所有锚标记文本
【发布时间】:2017-02-13 10:27:36
【问题描述】:

我有下面的html content,我想从中获取anchor tag 之间的所有文本

<div class="row mb-xlg"><div class="col-md-12">
<div class="heading heading-border heading-middle-border"><h3>Compatible Models</h3></div>
<div class="row show-grid">
<div class="col-md-4"><a href="/model/SFSPC19S80/_/_/Sanyo/PC19S80/" title="Sanyo PC19S80 Remote Control (Pc-27s80)">PC19S80</a></div>
<div class="col-md-4"><a href="/model/SFSPC25580/_/_/Sanyo/PC25580/" title="Sanyo PC25580 Remote Control (Pc-27s80)">PC25580</a></div>
<div class="col-md-4"><a href="/model/SFSPC25S80/_/_/Sanyo/PC25S80/" title="Sanyo PC25S80 Remote Control (Pc-27s80)">PC25S80</a></div>
<div class="col-md-4"><a href="/model/SFSPC27S80/_/_/Sanyo/PC27S80/" title="Sanyo PC27S80 Remote Control (Pc-27s80)">PC27S80</a></div>
</div></div></div>

我有下面的正则表达式,它返回anchor tag之间的所有文本

<a[^>]*>([^<]+)<\/a>+

this website 上测试

结果 -

Full match  `<a href="/model/SFSPC25580/_/_/Sanyo/PC25580/" title="Sanyo PC25580 Remote Control (Pc-27s80)">PC25580</a>`
Group 1.    `PC25580`
Match 3
Full match  `<a href="/model/SFSPC25S80/_/_/Sanyo/PC25S80/" title="Sanyo PC25S80 Remote Control (Pc-27s80)">PC25S80</a>`
Group 1.    `PC25S80`
Match 4
Full match  `<a href="/model/SFSPC27S80/_/_/Sanyo/PC27S80/" title="Sanyo PC27S80 Remote Control (Pc-27s80)">PC27S80</a>`
Group 1.    `PC27S80`

但我想添加Compatible Models这样的字条件

<h3>Compatible Models<\/h3>.*?<a[^>]*>([^<]+)<\/a>+

在这种情况下,它只返回第一个锚标记结果。 如何实现所有锚标记文本结果并存储在array

【问题讨论】:

    标签: php regex preg-match preg-match-all


    【解决方案1】:

    不要为此使用正则表达式。相反,您应该使用 DOM 解析器:

    下一个链接包含一个很好的答案,为什么你不应该使用正则表达式:

    【讨论】:

    • 如何使用 DOM Parser 获得相同的结果。你能解释一下吗
    猜你喜欢
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多