【问题标题】:PHP Regex to determine relative or absolute pathPHP Regex 确定相对或绝对路径
【发布时间】:2012-08-17 21:14:12
【问题描述】:

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

任何帮助将不胜感激。

【问题讨论】:

  • 我最近做了一些与此非常相似的事情:stackoverflow.com/questions/11759028/… - 这不是你想要的,但希望它能给你一个大致的想法/一个起点
  • 我不确定,但不是所有绝对 URL 都以协议开头,在几乎所有情况下都是“http://”?所以我想你可以检查 URL 是否以那个开头。
  • @DaveRandom - 它似乎正在工作,唯一的问题似乎是 html5 标签的问题,如“header”、“footer”、“nav”等......有什么想法吗?
  • @Fluidbyte 您能否展示一些您正在尝试处理的示例 HTML 源代码?

标签: php regex


【解决方案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;

【讨论】:

    【解决方案2】:

    正则表达式* 和 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,这通常是不受欢迎的。为了规避,您可以改用[DOMDocument][2],但如果没有任何问题,则不需要额外的代码。

    【讨论】:

      猜你喜欢
      • 2013-04-17
      • 2018-03-26
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 2013-11-30
      • 2015-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多