Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PHP has parse_url() but no build_url() #19

Open
jclaveau opened this issue Feb 12, 2022 · 0 comments
Open

PHP has parse_url() but no build_url() #19

jclaveau opened this issue Feb 12, 2022 · 0 comments

Comments

@jclaveau
Copy link

This discussion in stackoverflow explicits the problem in detail.

https://stackoverflow.com/questions/4354904/php-parse-url-reverse-parsed-url

The best solution seems, to me, to be https://stackoverflow.com/a/31691249/2714285 as it provides tests:

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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants