首页 > 解决方案 > 正则表达式匹配所有在锚点中包含特定单词的链接?

问题描述

我正在寻找 PHP 中的正则表达式来提取链接文本,其中包含锚文本中的特定单词(苹果、家庭、汽车)。

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

例如:

<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'

标签: phpregexregex-lookarounds

解决方案


您可以使用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>";
    }
}

演示

那会给你:

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

推荐阅读