我正在做一个脚本从一个网站得到所有的链接,但我想只得到一个特定的词的链接。我有下面的脚本,现在我可以得到所有的链接,我不知道如何创建一个正则表达式搜索我想要的词:
$url = file_get_contents("http://www.example.es");
preg_match_all("/<a(?:[^>]*)href='"([^'"]*)'"(?:[^>]*)>(?:[^<]*)<'/a>/is", $url, $todosenlaces);
如果您指的是特定的单词锚文本,您可以使用:
/<a.+href=["'](.*)["'].*>(.*(?:test|aa).*)<'/a>/isgmU
在上面的例子中,所有的锚都被发现在锚文本中有test
或aa
这个词。
如果你只想要锚中有特定的单词,你可以使用:
/<a[^>]+href=["']([^>]*(?:test|aa)[^>]*)["'][^>]*>(.*)<'/a>/isgmU
然而,这些并不是在所有情况下都有效,但对于简单的匹配,它们应该有效。
这样做:
$html = file_get_contents("http://www.example.es");
$dom = new DOMDocument();
$dom->loadHTML($html);
$results = array();
$tags = $dom->getElementsByTagName('a');
foreach ($tags as $tag) {
$url = $tag->getAttribute('href');
if (strpos($url,"apple") !== false){ //"apple" is the word to search for
$results[] = $url;
}
//or search for the word in the hyperlink text
if (strpos($tag->nodeValue,"apple") !== false){
$results[] = $url;
}
}
$results
将包含包含单词apple
的所有url的数组。
正如birdpspider已经指出的那样,使用RegEx搜索链接并不好。解析文档的代码来自:PHP字符串操作:Extract href .