1

我正在使用 cURL 来提取远程站点的内容。我需要检查所有“href=”属性并确定它们是相对路径还是绝对路径,然后获取链接的值并将其路径到类似 href="http://www.website.com/index.php ?url=[ABSOLUTE_PATH]"

任何帮助将不胜感激。

4

2 回答 2

1

如果我正确理解了问题,这是一种可能的解决方案:

$prefix = 'http://www.website.com/index.php?url=';
$regex = '~(<a.*?href\s*=\s*")(.*?)(".*?>)~is';
$html = file_get_contents('http://cnn.com');

$html = preg_replace_callback($regex, function($input) use ($prefix) {
  $parsed = parse_url($input[2]);

  if (is_array($parsed) && sizeof($parsed) == 1 && isset($parsed['path'])) {
    return $input[1] . $prefix . $parsed['path'] . $input[3];
  }
}, $html);

echo $html;
于 2012-08-17T21:32:53.977 回答
1

正则表达式*和 HTML 的组合parse_url()应该有助于:

// find all links in a page used within href="" or href='' syntax
$links = array();
preg_match_all('/href=(?:(?:"([^"]+)")|(?:\'([^\']+)\'))/i', $page_contents, $links);

// iterate through each array and check if it's "absolute"
$urls = array();
foreach ($links as $link) {
    $path = $link;
    if ((substr($link, 0, 7) == 'http://') || (substr($link, 0, 8) == 'https://')) {
        // the current link is an "absolute" URL - parse it to get just the path
        $parsed = parse_url($link);
        $path = $parsed['path'];
    }
    $urls[] = 'http://www.website.com/index.php?url=' . $path;
}

要确定 URL 是否是绝对的,我只需检查 URL 的开头是否http://https://; 如果您的 URL 包含其他媒体,例如ftp://tel:,您可能还需要处理这些媒体。

这个解决方案确实使用正则表达式来解析 HTML,这通常是不受欢迎的。为了规避,您可以切换到 using [DOMDocument][2],但如果没有任何问题,则不需要额外的代码。

于 2012-08-17T21:33:45.940 回答