php解析字符串里所有URL地址的方法

yipeiwu_com5年前PHP代码库

本文实例讲述了php解析字符串里所有URL地址的方法。分享给大家供大家参考。具体如下:

<?php
// $html = the html on the page
// $current_url = the full url that the html came from
//(only needed for $repath)
// $repath = converts ../ and / and // urls to full valid urls
function pageLinks($html, $current_url = "", $repath = false){
  preg_match_all("/\<a.+?href=(\"|')(?!javascript:|#)(.+?)(\"|')/i", $html, $matches);
  $links = array();
  if(isset($matches[2])){
    $links = $matches[2];
  }
  if($repath && count($links) > 0 && strlen($current_url) > 0){
    $pathi   = pathinfo($current_url);
    $dir    = $pathi["dirname"];
    $base    = parse_url($current_url);
    $split_path = explode("/", $dir);
    $url    = "";
    foreach($links as $k => $link){
      if(preg_match("/^\.\./", $link)){
        $total = substr_count($link, "../");
        for($i = 0; $i < $total; $i++){
          array_pop($split_path);
        }
        $url = implode("/", $split_path) . "/" . str_replace("../", "", $link);
      }elseif(preg_match("/^\/\//", $link)){
        $url = $base["scheme"] . ":" . $link;
      }elseif(preg_match("/^\/|^.\//", $link)){
        $url = $base["scheme"] . "://" . $base["host"] . $link;
      }elseif(preg_match("/^[a-zA-Z0-9]/", $link)){
        if(preg_match("/^http/", $link)){
          $url = $link;
        }else{
          $url    = $dir . "/" . $link;
        }
      }
      $links[$k] = $url;
    }
  }
  return $links;
}
header("content-type: text/plain");
$url = "//www.jb51.net";
$html = file_get_contents($url);
// Gets links from the page:
print_r(pageLinks($html));
// Gets links from the page and formats them to a full valid url:
print_r(pageLinks($html, $url, true));

希望本文所述对大家的php程序设计有所帮助。

相关文章

页面乱码问题的根源及其分析

首先, 关闭PHP配置文件php.ini中的default_charset:1. 页面没有指定charset , Apache配置defaultcharst gbk , 页面文件编码是u...

php中的异常和错误浅析

本文主要介绍了php中的异常和错误,分享给大家供大家参考学习,下面来一起看看详细的介绍: 一、异常与错误 异常是指程序运行中不符合预期情况以及与正常流程不同的状况。错误则属于自身问题,...

Discuz! 5.0.0论坛程序中加入一段js代码,让会员点击下载附件前自动弹出提示窗口

你需要修改attachment.php文件 在根目录下  在$attachexists = $ispaid = FALSE;下...

php文件上传类完整实例

本文实例讲述了php文件上传类。分享给大家供大家参考,具体如下: /** $file=new class_file($file_array,"flash/"); $file->...

Json_decode 解析json字符串为NULL的解决方法(必看)

从APP端或从其他页面post,get过来的数据一般因为数组形式。因为数组形式不易传输,所以一般都会转json后再发送。本以为发送方json_encode(),接收方json_decod...