使用parse_url和编辑网址

问题描述 投票:-1回答:1

我知道这是一个简单的问题和我缺乏知识,但无法弄清楚这一点。

网址就像https://example.com/newcar

预期输出如下:

https://example.com/bmw/newcar

所以我试着写一个parse()。

function parse($urls){
        foreach($urls as $k => $val){
            $scheme = parse_url($val["scheme"]);
            $host = parse_url($val["host"]);
            $path = parse_url($val["path"]);

            $urls = $scheme . $host . "/" . "bmw" . $path;
        }

        return $urls;

    }

但显然parse()运行不正常。它给Illegal string offset 'scheme'错误。

php
1个回答
1
投票

对于您的情况,该功能存在各种问题,这是更新版本:

function parse($urls) {
    // prepare the result
    $result = [];

    foreach($urls as $url){
        // pass the whole url to parse_url
        $parts = parse_url($url);

        // then reference the parts from that result
        // and add the final version to the to-be-returned-result
        $result[] = $parts['scheme'] . '://' . $parts['host'] . '/bmw' . $parts['path'];
    }

    return $result;
}

print_r(parse([
    'https://example.com/newcar'
]));

https://3v4l.org/X9Q2H

© www.soinside.com 2019 - 2024. All rights reserved.