10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

build_url (parse_urlの逆)

Last updated at Posted at 2015-09-02

PECLのhttp_build_urlとの互換性はありません。

関数定義
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]" : '')
    ;
}
例 (コード)
<?php

$patterns = [
    ['host' => 'example.com'],
    ['scheme' => 'https', 'host' => 'example.com'],
    ['scheme' => 'http', 'host' => 'example.com', 'port' => 8080, 'path' => '/x/y/z'],
    ['scheme' => 'http', 'host' => 'example.com', 'port' => 8080, 'user' => 'anonymous', 'query' => 'a=b&c=d', 'fragment' => 'xyz'],
    ['scheme' => 'http', 'host' => 'example.com', 'user' => 'root', 'pass' => 'stupid', 'path' => '/x/y/z', 'query' => ['a' => 'b', 'c' => 'd']],
    ['path' => '/x/y/z', 'query' => 'a=b&c=d'],
];

foreach ($patterns as $pattern) {
    echo json_encode($pattern, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n/* " . build_url($pattern) . " */\n\n";
}
例 (結果)
{
    "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://anonymous@example.com: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:stupid@example.com/x/y/z?a=b&c=d */

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

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?