欢迎阅读「 自定义函数之formaturl,格式化相对网址 」

自定义函数之formaturl,格式化相对网址

网站技术 ayflying 3218℃ 评论

有时候我们需要采集内容,有些网页上面显示的是相对地址,这时候我们需要一个方法来格式化这些网址,让这些相对网址都转为带域名的绝对网址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
 * 网址补全
 * @param string $url 访问的网址
 * @param string $str 需要格式化的相对地址
 * @return array|mixed|string
 */
function formaturl($url$str)
{
    if (stripos($str'http://') === 0 || stripos($str'ftp://') === 0) {
        return $str;
    }
    $str str_replace('\\''/'$str);
    $parseUrl parse_url(dirname($url) . '/');
    $scheme = isset($parseUrl['scheme']) ? $parseUrl['scheme'] : 'http';
    $host $parseUrl['host'];
    $path = isset($parseUrl['path']) ? $parseUrl['path'] : '';
    $port = isset($parseUrl['port']) ? $parseUrl['port'] : '';
    if (strpos($str'/') === 0) {
        return $scheme '://' $host $str;
    else {
        $part explode('/'$path);
        array_shift($part);
        $count = substr_count($str'../');
        if ($count > 0) {
            for ($i = 0; $i <= $count$i++) {
                array_pop($part);
            }
        }
        $path = implode('/'$part);
        $str str_replace(array('../''./'), ''$str);
        $path $path == '' '/' '/' . trim($path'/') . '/';
        return $scheme '://' $host $path $str;
    }
}


转载请注明:七彩悠悠博客 | 心悠悠 情悠悠 » 自定义函数之formaturl,格式化相对网址

收藏文章
表情删除后不可恢复,是否删除
取消
确定
图片正在上传,请稍后...
评论内容为空!
还没有评论,快来抢沙发吧!
按钮 内容不能为空!
立刻说两句吧! 查看0条评论

高效,专业,悠悠博客

联系我们