首页 > 开发 > PHP > 正文

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

2024-05-04 23:33:53
字体:大 中 小
来源:转载
供稿:网友

这篇文章主要介绍了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 = "http://www.vevb.com"; 
  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)); 

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表