欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php 正则表达式提取网页超级链接url的函数

程序员文章站 2022-06-22 14:31:58
复制代码 代码如下:function match_links($document) { preg_match_all("'<\s*a\s.*?href\s*=\s*(...
复制代码 代码如下:

function match_links($document) {
preg_match_all("'<\s*a\s.*?href\s*=\s*([\"\'])?(?(1)(.*?)\\1|([^\s\>]+))[^>]*>?(.*?)</a>'isx",$document,$links);
while(list($key,$val) = each($links[2])) {
if(!empty($val))
$match['link'][] = $val;
}
while(list($key,$val) = each($links[3])) {
if(!empty($val))
$match['link'][] = $val;
}
while(list($key,$val) = each($links[4])) {
if(!empty($val))
$match['content'][] = $val;
}
while(list($key,$val) = each($links[0])) {
if(!empty($val))
$match['all'][] = $val;
}
return $match;
}

主要是正则的问题,下面给出个asp.net下的,多测试正则
获取页面的链接正则
复制代码 代码如下:

public string gethref(string htmlcode)
{
string matchvale = "";
string reg = @"(h|h)(r|r)(e|e)(f|f) *= *('|"")?((\w|\\|\/|\.|:|-|_)+)('|""| *|>)?";
foreach (match m in regex.matches(htmlcode, reg))
{
matchvale += (m.value).tolower().replace("href=", "").trim() + "||";
}
return matchvale;
}