Php 正则表达式匹配锚中包含特定单词的所有链接?
我正在寻找一个PHP正则表达式来提取链接,一个包含锚文本中特定单词apple、home、car的文本 重要提示:链接的格式事先不知道 例如: 我的模式:Php 正则表达式匹配锚中包含特定单词的所有链接?,php,regex,regex-lookarounds,Php,Regex,Regex Lookarounds,我正在寻找一个PHP正则表达式来提取链接,一个包含锚文本中特定单词apple、home、car的文本 重要提示:链接的格式事先不知道 例如: 我的模式: /<a.*?href="(.*)".*?>apple|car|home<\/a>/i 更新:这种模式有效 '/<a.+href=["\'](.*)["\'].*>(.*(?:apple|car|home).*)<\/a>/iU' 您可以使用和来获取和一个正则表达式,其中包含要查找的单词的替换项
/<a.*?href="(.*)".*?>apple|car|home<\/a>/i
更新:这种模式有效
'/<a.+href=["\'](.*)["\'].*>(.*(?:apple|car|home).*)<\/a>/iU'
您可以使用和来获取和一个正则表达式,其中包含要查找的单词的替换项,并添加单词边界,以确保这些单词不是更大匹配的一部分。为了说明不区分大小写,可以使用/i标志
我在RegEx非常糟糕,但这里有一个起点。亚历克斯,谢谢你的帮助
/<a.*?href="(.*)".*?>apple|car|home<\/a>/i
'/<a.+href=["\'](.*)["\'].*>(.*(?:apple|car|home).*)<\/a>/iU'
$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