当前位置:首页 > PHP教程 > php应用 > 列表

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

发布:smiling 来源: PHP粉丝网  添加日期:2021-05-21 11:55:07 浏览: 评论:0 

这篇文章主要介绍了php解析字符串里所有URL地址的方法,涉及php操作数组、字符串及URL的技巧,具有一定参考借鉴价值,需要的朋友可以参考下.

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

  1. <?php 
  2. // $html = the html on the page 
  3. // $current_url = the full url that the html came from 
  4. //(only needed for $repath) 
  5. // $repath = converts ../ and / and // urls to full valid urls 
  6. function pageLinks($html, $current_url = "", $repath = false){ 
  7.   preg_match_all("/\<a.+?href=(\"|')(?!javascript:|#)(.+?)(\"|')/i", $html, $matches); 
  8.   $links = array(); 
  9.   if(isset($matches[2])){ 
  10.     $links = $matches[2]; 
  11.   } 
  12.   if($repath && count($links) > 0 && strlen($current_url) > 0){ 
  13.     $pathi   = pathinfo($current_url); 
  14.     $dir    = $pathi["dirname"]; 
  15.     $base    = parse_url($current_url); 
  16.     $split_path = explode("/", $dir); 
  17.     $url    = ""; 
  18.     foreach($links as $k => $link){ 
  19.       if(preg_match("/^\.\./", $link)){ 
  20.         $total = substr_count($link, "../"); 
  21.         for($i = 0; $i < $total; $i++){ 
  22.           array_pop($split_path); 
  23.         } 
  24.         $url = implode("/", $split_path) . "/" . str_replace("../", "", $link); 
  25.       }elseif(preg_match("/^\/\//", $link)){ 
  26.         $url = $base["scheme"] . ":" . $link; 
  27.       }elseif(preg_match("/^\/|^.\//", $link)){ 
  28.         $url = $base["scheme"] . "://" . $base["host"] . $link; 
  29.       }elseif(preg_match("/^[a-zA-Z0-9]/", $link)){ 
  30.         if(preg_match("/^http/", $link)){ 
  31.           $url = $link; 
  32.         }else{ 
  33.           $url    = $dir . "/" . $link; 
  34.         } 
  35.       } 
  36.       $links[$k] = $url; 
  37.     } 
  38.   } 
  39.   return $links; 
  40. } 
  41. header("content-type: text/plain"); 
  42. $url = "https://www.jb51.net"; 
  43. $html = file_get_contents($url); 
  44. // Gets links from the page: 
  45. print_r(pageLinks($html)); 
  46. // Gets links from the page and formats them to a full valid url: 
  47. print_r(pageLinks($html, $url, true));

Tags: php解析字符串

分享到: