php parse_url reverse -- 解析后的url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4354904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:46:57  来源:igfitidea点击:

php parse_url reverse -- parsed url

phpparse-url

提问by Val

Is there a way to reverse the url from a parsed url?

有没有办法从解析的 url 中反转 url?

$url = 'http://www.domain.com/dir/index.php?query=blabla#more_bla';
$parse = parse_url($url);
print_r($parse);
/*
array(
 'scheme'=>'http://',
 etc....
)
*/
$revere = reverse_url($parse); // probably does not exist but u get the point

echo $reverse;
//outputs:// "http://www.domain.com/dir/index.php?query=blabla#more_bla"

Or if there is a way validate a url that is missing part of its recommended urls e.g

或者,如果有一种方法可以验证缺少部分推荐网址的网址,例如

www.mydomain.com

www.mydomain.com

mydomain.com

mydomain.com

should all return http://www.mydomain.comor with correct sub domain

应该全部返回 http://www.mydomain.com或使用正确的子域

采纳答案by Brad Mace

You should be able to do

你应该能够做到

http_build_url($parse)

NOTE: http_build_urlis only available by installing pecl_http.

注意:http_build_url只能通过安装 pecl_http 来使用。

According to the docs it's designed specifically to handle the output from parse_url. Both functions handle anchors, query params, etc so there are no "other properties not mentioned on the $url".

根据文档,它专门设计用于处理来自parse_url. 这两个函数都处理锚点、查询参数等,因此没有“$url 上未提及的其他属性”。

To add http://when it's missing, use a basic check before parsing it:

http://在丢失时添加,请在解析之前使用基本检查:

if (strpos($url, "http://") != 0)
    $url = "http://$url";

回答by NobleUplift

These are the two functions I use for decomposing and rebuilding URLs:

这是我用于分解和重建 URL 的两个函数:

function http_parse_query($query) {
    $parameters = array();
    $queryParts = explode('&', $query);
    foreach ($queryParts as $queryPart) {
        $keyValue = explode('=', $queryPart, 2);
        $parameters[$keyValue[0]] = $keyValue[1];
    }
    return $parameters;
}

function build_url(array $parts) {
    return (isset($parts['scheme']) ? "{$parts['scheme']}:" : '') . 
        ((isset($parts['user']) || isset($parts['host'])) ? '//' : '') . 
        (isset($parts['user']) ? "{$parts['user']}" : '') . 
        (isset($parts['pass']) ? ":{$parts['pass']}" : '') . 
        (isset($parts['user']) ? '@' : '') . 
        (isset($parts['host']) ? "{$parts['host']}" : '') . 
        (isset($parts['port']) ? ":{$parts['port']}" : '') . 
        (isset($parts['path']) ? "{$parts['path']}" : '') . 
        (isset($parts['query']) ? "?{$parts['query']}" : '') . 
        (isset($parts['fragment']) ? "#{$parts['fragment']}" : '');
}

// Example
$parts = parse_url($url);

if (isset($parts['query'])) {
    $parameters = http_parse_query($parts['query']);
    foreach ($parameters as $key => $value) {
        $parameters[$key] = $value; // do stuff with $value
    }
    $parts['query'] = http_build_query($parameters);
}

$url = build_url($parts);

回答by Jesse

This function should do the trick:

这个函数应该可以解决问题:

function unparse_url(array $parsed): string {
    $pass      = $parsed['pass'] ?? null;
    $user      = $parsed['user'] ?? null;
    $userinfo  = $pass !== null ? "$user:$pass" : $user;
    $port      = $parsed['port'] ?? 0;
    $scheme    = $parsed['scheme'] ?? "";
    $query     = $parsed['query'] ?? "";
    $fragment  = $parsed['fragment'] ?? "";
    $authority = (
        ($userinfo !== null ? "$userinfo@" : "") .
        ($parsed['host'] ?? "") .
        ($port ? ":$port" : "")
    );
    return (
        (\strlen($scheme) > 0 ? "$scheme:" : "") .
        (\strlen($authority) > 0 ? "//$authority" : "") .
        ($parsed['path'] ?? "") .
        (\strlen($query) > 0 ? "?$query" : "") .
        (\strlen($fragment) > 0 ? "#$fragment" : "")
    );
}

Here is a short test for it:

这是一个简短的测试:

function unparse_url_test() {
    foreach ([
        '',
        'foo',
        'http://www.google.com/',
        'http://u:p@foo:1/path/path?q#frag',
        'http://u:p@foo:1/path/path?#',
        'ssh://root@host',
        '://:@:1/?#',
        'http://:@foo:1/path/path?#',
        'http://@foo:1/path/path?#',
    ] as $url) {
        $parsed1 = parse_url($url);
        $parsed2 = parse_url(unparse_url($parsed1));

        if ($parsed1 !== $parsed2) {
            print var_export($parsed1, true) . "\n!==\n" . var_export($parsed2, true) . "\n\n";
        }
    }
}

unparse_url_test();

回答by mpyw

Another implemention:

另一个实现:

function build_url(array $elements) {
    $e = $elements;
    return
        (isset($e['host']) ? (
            (isset($e['scheme']) ? "$e[scheme]://" : '//') .
            (isset($e['user']) ? $e['user'] . (isset($e['pass']) ? ":$e[pass]" : '') . '@' : '') .
            $e['host'] .
            (isset($e['port']) ? ":$e[port]" : '')
        ) : '') .
        (isset($e['path']) ? $e['path'] : '/') .
        (isset($e['query']) ? '?' . (is_array($e['query']) ? http_build_query($e['query'], '', '&') : $e['query']) : '') .
        (isset($e['fragment']) ? "#$e[fragment]" : '')
    ;
}

The results should be:

结果应该是:

{
    "host": "example.com"
}
/* //example.com/ */

{
    "scheme": "https",
    "host": "example.com"
}
/* https://example.com/ */

{
    "scheme": "http",
    "host": "example.com",
    "port": 8080,
    "path": "/x/y/z"
}
/* http://example.com:8080/x/y/z */

{
    "scheme": "http",
    "host": "example.com",
    "port": 8080,
    "user": "anonymous",
    "query": "a=b&c=d",
    "fragment": "xyz"
}
/* http://[email protected]:8080/?a=b&c=d#xyz */

{
    "scheme": "http",
    "host": "example.com",
    "user": "root",
    "pass": "stupid",
    "path": "/x/y/z",
    "query": {
        "a": "b",
        "c": "d"
    }
}
/* http://root:[email protected]/x/y/z?a=b&c=d */

{
    "path": "/x/y/z",
    "query": "a=b&c=d"
}
/* /x/y/z?a=b&c=d */

回答by Tomasz Kap?oński

This answer is appendix to accepted answer by @BradMace. I originally added this as a comment but he suggested add this as separate answer so here it is.

这个答案是@BradMace 接受的答案的附录。我最初将其添加为评论,但他建议将其添加为单独的答案,所以在这里。

Original answer to use http_build_url($parse)provided by pecl_httpwould work for extension version 1.x- versions 2.xand later are object oriented and syntax changed.

原来答案使用http_build_url($parse)提供pecl_http将工作扩展版本1.x-版本2.x及更高版本的面向对象和语法改变。

In newer version (tested on pecl_http v.3.2.3) implementation should be:

在较新版本(已测试pecl_http v.3.2.3)中,实现应该是:

$httpUrl = new \http\Url($parsed);
$url = $httpUrl->toString();

回答by Jayant Pandey

Get last string from url eg: http://example.com/controllername/functionnameand need to get functionname

从 url 获取最后一个字符串,例如:http: //example.com/controllername/functionname并且需要获取 functionname

$referer = explode('/',strrev($_SERVER['HTTP_REFERER']));

$referer = expand('/',strrev($_SERVER['HTTP_REFERER']));

$lastString = strrev($referer[0]);

$lastString = strrev($referer[0]);