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程序设计有所帮助。

相关文章

Windows 下安装 swoole 图文教程(php)

Windows 下安装 swoole 图文教程(php)

Windows 下安装 swoole 具体步骤: Swoole,原本不支持在Windows下安装的,所以我们要安装Cygwin来使用。在安装Cygwin下遇到了很多坑,百度经验上的文档不...

php实现用户在线时间统计详解

首先介绍一下所涉及的数据表结构,四个字段: 代码如下: 复制代码 代码如下: uid<int(10)> :用户id session_id<varchar(40)>...

PHP 处理图片的类实现代码

复制代码 代码如下: <?php /** * author:yagas * email:yagas60@21cn.com */ class Image { /** 类保护变量 */...

浅谈Eclipse PDT调试PHP程序

1. 下载eclipse,从官网上找就可以了,并确认当前系统中有java环境,即jdk和jre。 2. 安装pdt了,采用的是在线安装,更新地址在默认中已经包含了。只是更新起来比较麻烦。...

php带密码功能并下载远程文件保存本地指定目录 修改加强版

php带密码功能并下载远程文件保存本地指定目录 修改加强版

原作者BlueStyle 提示 改进地方有 以前的算法是等文件下载完才计算, 现在这个直接在在获取文件时候就计算大小 加了容错语句 增加了判断目录,没有目录自动创建 把计算文件大小的算法...