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

yipeiwu_com6年前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实现的中文分词类完整实例

本文实例讲述了php实现的中文分词类。分享给大家供大家参考,具体如下: 该中文分词类源码使用http://tools.jb51.net/code/jb51_php_format进行了格式...

php实现遍历多维数组的方法

本文实例讲述了php实现遍历多维数组的方法。分享给大家供大家参考,具体如下: $a=array('fruits'=>array('a'=>'orange','b'=>...

php实现按照权重随机排序数据的方法

本文实例讲述了php实现按照权重随机排序数据的方法。分享给大家供大家参考。 具体实现方法如下: 复制代码 代码如下: <?php   /** ...

PHP伪静态Rewrite设置之APACHE篇

 一、Apache配置:   1、支持httpd.conf 配置 2、支持目录 .htaccess配置(一种"分布式配置"文件针对虚拟空间,空间商不让修改Apache...