【问题标题】:Regular expression to match all links that contain specifics words in anchor?正则表达式匹配所有在锚点中包含特定单词的链接?
【发布时间】:2018-06-04 17:43:34
【问题描述】:

我正在寻找 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'

【问题讨论】:

  • 我在 RegEx 上很糟糕,但这里是你的起点。 [^&lt;]*(&lt;a href="([^"]+)"&gt;([^&lt;]+)&lt;\/a&gt;)Group 1: StringGroup 2: HrefGroup 3: Text。您真正需要做的就是弄清楚如何multiline 匹配以及如何比较Group 3Regex101 Link
  • @Alex,谢谢你的帮助

标签: php regex regex-lookarounds


【解决方案1】:

您可以使用DOMDocument 并使用getElementsByTagName 来获取&lt;a&gt; 元素。

然后您可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多