寫采集必用的函數,URL補全函數,也可叫做FormatUrl。
寫此函數作用就是為了開發采集程序,采集文章的時候會經常遇到頁面里的路徑是 “相對路徑” 或者 “絕對根路徑” 不是“絕對全路徑”就無法收集URL。
所以,就需要本功能函數進行對代碼進行格式化,把所有的超鏈接都格式化一遍,這樣就可以直接收集到正確的URL了。
路徑知識普及
相對路徑:“../” “./” 或者前面什么都不加
絕對根路徑:/path/xxx.html
絕對全路徑:http://www.xxx.com/path/xxx.html
使用實例:
- <?php
- $surl="http://www.soqi.cc/";
- $gethtm = '<a href="/">首頁</a><a href="/daxue/">大學排行</a>';
- echo formaturl($gethtm,$surl);
- ?>
輸出:
- <a href=http://www.soqi.cc>首頁</a><a href=http://www.soqi.cc/daxue/>大學排行</a>
函數代碼如下:
- <?php
- function formaturl($l1, $l2) {
- if (preg_match_all ( "/(<img[^>]+src=/"([^/"]+)/"[^>]*>)|(<a[^>]+href=/"([^/"]+)/"[^>]*>)|(<img[^>]+src='([^']+)'[^>]*>)|(<a[^>]+href='([^']+)'[^>]*>)/i", $l1, $regs )) {
- foreach ( $regs [0] as $num => $url ) {
- $l1 = str_replace ( $url, lIIIIl ( $url, $l2 ), $l1 );
- }
- }
- return $l1;
- }
- function lIIIIl($l1, $l2) {
- if (preg_match ( "/(.*)(href|src)/=(.+?)( |///>|/>).*/i", $l1, $regs )) {
- $I2 = $regs [3];
- }
- if (strlen ( $I2 ) > 0) {
- $I1 = str_replace ( chr ( 34 ), "", $I2 );
- $I1 = str_replace ( chr ( 39 ), "", $I1 );
- } else {
- return $l1;
- }
- $url_parsed = parse_url ( $l2 );
- $scheme = $url_parsed ["scheme"];
- if ($scheme != "") {
- $scheme = $scheme . "://";
- }
- $host = $url_parsed ["host"];
- $l3 = $scheme . $host;
- if (strlen ( $l3 ) == 0) {
- return $l1;
- }
- $path = dirname ( $url_parsed ["path"] );
- if ($path [0] == "//") {
- $path = "";
- }
- $pos = strpos ( $I1, "#" );
- if ($pos > 0)
- $I1 = substr ( $I1, 0, $pos );
- //判斷類型
- if (preg_match ( "/^(http|https|ftp):(////|////)(([/w/////+/-~`@:%])+/.)+([/w/////./=/?/+/-~`@/':!%#]|(&)|&)+/i", $I1 )) {
- return $l1;
- } //http開頭的url類型要跳過
- elseif ($I1 [0] == "/") {
- $I1 = $l3 . $I1;
- } //絕對路徑
- elseif (substr ( $I1, 0, 3 ) == "../") { //相對路徑
- while ( substr ( $I1, 0, 3 ) == "../" ) {
- $I1 = substr ( $I1, strlen ( $I1 ) - (strlen ( $I1 ) - 3), strlen ( $I1 ) - 3 );
- if (strlen ( $path ) > 0) {
- $path = dirname ( $path );
- }
- }
- $I1 = $l3 . $path . "/" . $I1;
- } elseif (substr ( $I1, 0, 2 ) == "./") {
- $I1 = $l3 . $path . substr ( $I1, strlen ( $I1 ) - (strlen ( $I1 ) - 1), strlen ( $I1 ) - 1 );
- } elseif (strtolower ( substr ( $I1, 0, 7 ) ) == "mailto:" || strtolower ( substr ( $I1, 0, 11 ) ) == "javascript:") {
- return $l1;
- } else {
- $I1 = $l3 . $path . "/" . $I1;
- }
- return str_replace ( $I2, "/"$I1/"", $l1 );
- }
- ?>
新聞熱點
疑難解答