因为一些学习和研究目的,最近在写一些数据抓取的组件,在网页上很常见的是相对链接,有时候因为所在网页和相对链接的关系不太确定,所以就需要转换一下,本来这个功能实在太简单,直接在网上搜索了一下,但是发现绝大部分代码都是错的,或者说不严谨,随便改一个目录深度就会发生错误。 这里贴一下我的解决方案:
<?php
class spider{
/*
$rel string 相对链接
$baseURL string 当前所在页面完整地址
*/
public function absoluteURL( $rel, $baseURL ): string
{
// 忽略绝对地址
if ( strstr( $rel, 'https:/') || strstr($rel,'http:/') || strstr($rel,':/') ){
return $rel;
}
// 结构化当前URL
$url = parse_url($baseURL);
$rel = trim($rel);
$depthPath = [];
foreach ( explode('/',$url['path']) as $i => $p ){
if( $p != '' ){
$depthPath[] = $p;
}
}
$pathDeep = count($depthPath);
$relDepth = [];
$rootPath = false;
$backPathDepth = 0;
if( strstr($rel,'/') ){
foreach ( explode("/",$rel) as $i => $r){
if( $i==0 && $r == '' ){ // 直接根目录
$rootPath = true;
}
if( $r != '' ){
$relDepth[] = $r;
}
if( $r === '..' ){
$backPathDepth++;
}
}
}else{
$relDepth = [$rel];
}
$new_url = $url['scheme'] . '://' . $url['host'];
if( !$rootPath ){
for( $i = 0; $i < $pathDeep - $backPathDepth; $i++ ){
$new_url .= ('/' . $depthPath[$i]);
}
}
for ( $i = 0; $i < count($relDepth); $i ++ ){
if( $relDepth[$i] !== '..' && $relDepth[$i] !== '.' ){
$new_url .= ('/' . $relDepth[$i]);
}
}
return $new_url;
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有