php - 正则表达式匹配所有在锚点中包含特定单词的链接?
问题描述
我正在寻找 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'
解决方案
您可以使用DOMDocument并使用getElementsByTagName来获取<a>
元素。
然后,您可以使用preg_match和正则表达式与您要查找的单词交替使用并添加单词边界以确保单词不是更大匹配的一部分。要考虑不区分大小写,您可以使用该/i
标志。
$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
推荐阅读
- java - 将 TestIdentity / LegaIdentity 添加到 StartedMockNode
- webrtc - WebRTC 连接g 只发送一个候选人
- python - 基于匹配多个键:值对在列表中组合字典
- .net-core - OData.Client.DataServiceContext 在调用 SSL 服务器后返回空列表
- ios - 使用 shell 脚本将 dSYM/.symbols 文件上传到 appstore 自动连接
- angular - 以安全的方式从部署在 App 引擎上的 Angular 应用程序调用 http 云功能
- firebase - 映射集合时获取 Firestore 文档 ID
- java - 如何使用 Java SDK v12 删除 Blob 文件夹
- dart - SetState 调用阻止访问由流更新的字段
- javascript - 闪亮模式对话框中的单选按钮