正则表达式匹配包含锚中特定单词的所有链接?

时间:2018-05-31 15:24:30

标签: php regex regex-lookarounds

我正在寻找PHP中的正则表达式,以在锚文本中提取包含特定单词(apple,home,car)的文本链接。

重要提示:事先不知道链接的格式。

E.g:

<a href="fruit.html">The Apple red</a>
<a href="Construction.html#one">The big Home</a>
<a href="automotive.html?lang=en">Car for rent</a>

期望的结果:

fruit.html
Construction.html#one
automotive.html?lang=en

我的模式:

/<a.*?href="(.*)".*?>apple|car|home<\/a>/i

更新:此模式有效

'/<a.+href=["\'](.*)["\'].*>(.*(?:apple|car|home).*)<\/a>/iU'

1 个答案:

答案 0 :(得分:1)

您可以使用DOMDocument并使用getElementsByTagName获取<a>元素。

然后,您可以使用preg_match和正则表达式与您要查找的单词进行交替,并添加单词边界以确保单词不是较大匹配的一部分。要考虑不区分大小写,可以使用/i标记。

\b(?:apple|big|car)\b

$data = <<<DATA
<a href="fruit.html">The Apple red</a>
<a href="Construction.html#one">The big Home</a>
<a href="automotive.html?lang=en">Car for rent</a>
<a href="fruit.html">The Pineapple red</a>
<a href="Construction.html#one">The biggest Home</a>
<a href="automotive.html?lang=en">Cars for rent</a>
DATA;

$dom = new DOMDocument();
$dom->loadHTML($data);

foreach($dom->getElementsByTagName("a") as $element) {
    if (preg_match('#\b(?:apple|big|car)\b#i', $element->nodeValue)) {
        echo $element->getAttribute("href") . "<br>";
    }
}

Demo

那会给你:

fruit.html
Construction.html#one
automotive.html?lang=en