php parse_url 反向 -- 解析后的 url

发布于 2024-10-05 15:31:25 字数 554 浏览 2 评论 0原文

有没有办法从解析的 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"

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

www.mydomain.com

mydomain.com

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

Is there a way to reverse the url from a parsed 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

mydomain.com

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

烈酒灼喉 2024-10-12 15:31:25

这是我用来分解和重​​建 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);

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

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);
梅倚清风 2024-10-12 15:31:25

您应该能够执行

http_build_url($parse)

以下操作注意: http_build_url 仅可通过安装 pecl_http。

根据文档,它是专门为处理 parse_url 的输出而设计的。这两个函数都处理锚点、查询参数等,因此不存在“$url 上未提及的其他属性”。

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

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

You should be able to do

http_build_url($parse)

NOTE: http_build_url is only available by installing 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".

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

if (strpos($url, "http://") != 0)
    $url = "http://$url";
八巷 2024-10-12 15:31:25

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

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" : "")
    );
}

这是一个简短的测试:

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();

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();
才能让你更想念 2024-10-12 15:31:25

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

使用 pecl_http 提供的 http_build_url($parse) 的原始答案适用于扩展版本 1.x - 版本 2.x< /code> 及更高版本是面向对象的并且语法发生了变化。

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

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

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.

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

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

$httpUrl = new \http\Url($parsed);
$url = $httpUrl->toString();
无所的.畏惧 2024-10-12 15:31:25

十年后,使用几十年前的方法:)

考虑到您将永远拥有该计划和;主持人。 (可选)路径、查询和片段偏移:

$a = parse_url('https://example.com/whatever-season/?drink=water&sleep=better');

使用优雅的 sprintf 进行重建:

function buildUrl(array $a){
        return sprintf('%s://%s%s%s%s',
                            $a['scheme'], $a['host'], $a['path'] ?? '',
                            $a['query'] ? '?' . $a['query'] : '',
                            $a['fragment'] ? '#' . $a['fragment'] : '');
}

其中 path 偏移由 空合并运算符 (PHP 7+)。

A decade later using the decades old method :)

Considering you will always have the scheme & host. Optionally, path, query and fragment offsets:

$a = parse_url('https://example.com/whatever-season/?drink=water&sleep=better');

Build back with classy sprintf:

function buildUrl(array $a){
        return sprintf('%s://%s%s%s%s',
                            $a['scheme'], $a['host'], $a['path'] ?? '',
                            $a['query'] ? '?' . $a['query'] : '',
                            $a['fragment'] ? '#' . $a['fragment'] : '');
}

Where path offset is operated by the null coalescing operator (PHP 7+).

迷离° 2024-10-12 15:31:25

另一个实现:

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]" : '')
    ;
}

结果应该是:

{
    "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 */

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 */
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文