在URL中将URL拆分/解析为其组成部分

时间:2017-10-17 18:27:07

标签: php url url-parsing

将URL解析为相应路径的最佳方法是什么,例如

https://www.example.com/path/to/directory/file.jpeg?param1=foo&param2=bar

保存数组的结果

Array(
    ["scheme"] => "https",
    ["host"] => www.example.com
    ["directory"] => "path/to/directory"
    ["filename"] => "file"
    ["extension] => "jpeg"
    ["path"] => "path/to/directory/file.jpeg",
    ["file"] => "file.jpeg"
    ["params"] => Array(
        ["param1"] => "foo",
        ["param2"] => "bar"
    )
)

注意:这些键不​​需要这样命名,它们只是一个例子。

我已经研究过parse_url,但它并没有将细分的路径分开,所以进一步的手动处理似乎是不可避免的。

旁注:我调查了very many multiple questionsanswers,但我无法做到找到任何明确的参考,因此我的问题。

1 个答案:

答案 0 :(得分:4)

最好的方法是结合多个内置php函数的工作,例如parse_url(对于基本url部分),parse_str(对于查询参数)和pathinfo(对于目录,文件名和扩展部分)。

parse_url

parse_url将解析url并将其拆分为包含以下键的关联数组(如果它们存在于url中):

  • scheme(http,https,ftp,...)
  • 主持人(www.example.com)
  • 端口
  • 用户
  • 传递
  • 路径(这需要进一步处理)
  • 查询(这需要进一步处理)
  • 片段(锚点/ hashbang部分,哈希标记后面的任何内容)

parse_str

parse_str可用于将query部分从parse_url解析为多维(如果需要)关联数组。

PATHINFO

pathinfo可用于将path部分从parse_url解析为一个关联数组,该数组可包含以下键:

[dirname] => /path/to/directory
[basename] => file.jpeg
[extension] => jpeg
[filename] => file

全部放在一起

function decompose_url($url) {
    $parts = parse_url($url);
    if (!$parts) {
        # For seriously malformed urls
        return false;
    }
    # Just for good measure, throw in the top level domain, if there is a host with a top level domain
    if (array_key_exists('host', $parts) && strrpos($parts['host'], '.') !== false) {
        $domain_parts = explode('.', $parts['host']);
        $parts['tld'] = end($domain_parts);
    }
    if (array_key_exists('path', $parts)) {
        $pathinfo = pathinfo($parts['path']);
        if (empty($pathinfo['basename'])) {
            # With an empty basename, extension and filename will also be empty
            unset($pathinfo['basename']);
            unset($pathinfo['extension']);
            unset($pathinfo['filename']);

        }
        $parts = array_merge($parts, $pathinfo);
    }
    if (array_key_exists('query', $parts)) {
        parse_str($parts['query'], $query_parts);
        $parts['query_parts'] = $query_parts;
    }
    return $parts;
}

给它一个测试

$urls = [
    'http://www.example.com/',
    'http://www.example.com',
    'http://www.example.com/test/.jpg',
    'http://www.example.com/test/.'
    'https://anonymous:dCU7egW1A1L0a6pxU3qu9@www.example.com:8080/path/to/directory/file.jpeg?param1=foo&param2=bar&param3[1]=abc&param3[2]=def#anchor',
    'ftp://anonymous@ftp.example.com/pub/test.jpg',
    'file:///home/user/.config/test.config',
    'chrome://settings/passwords',
];

foreach ($urls as $url) {
    echo $url, PHP_EOL;
    var_export(decompose_url($url));
    echo PHP_EOL, PHP_EOL;
}

将产生这些相应的结果:

http://www.example.com/
array (
  'scheme' => 'http',
  'host' => 'www.example.com',
  'path' => '/',
  'tld' => 'com',
  'dirname' => '/',
)

http://www.example.com
array (
  'scheme' => 'http',
  'host' => 'www.example.com',
  'tld' => 'com',
)

http://www.example.com/test/.jpg
array (
  'scheme' => 'http',
  'host' => 'www.example.com',
  'path' => '/test/.jpg',
  'tld' => 'com',
  'dirname' => '/test',
  'basename' => '.jpg',
  'extension' => 'jpg',
  'filename' => '',
)

http://www.example.com/test/.
array (
  'scheme' => 'http',
  'host' => 'www.example.com',
  'path' => '/test/.',
  'tld' => 'com',
  'dirname' => '/test',
  'basename' => '.',
  'extension' => '',
  'filename' => '',
)

https://anonymous:dCU7egW1A1L0a6pxU3qu9@www.example.com:8080/path/to/directory/file.jpeg?param1=foo&param2=bar&param3[1]=abc&param3[2]=def#anchor
array (
  'scheme' => 'https',
  'host' => 'www.example.com',
  'port' => 8080,
  'user' => 'anonymous',
  'pass' => 'dCU7egW1A1L0a6pxU3qu9',
  'path' => '/path/to/directory/file.jpeg',
  'query' => 'param1=foo&param2=bar&param3[1]=abc&param3[2]=def',
  'fragment' => 'anchor',
  'tld' => 'com',
  'dirname' => '/path/to/directory',
  'basename' => 'file.jpeg',
  'extension' => 'jpeg',
  'filename' => 'file',
  'query_parts' => 
  array (
    'param1' => 'foo',
    'param2' => 'bar',
    'param3' => 
    array (
      1 => 'abc',
      2 => 'def',
    ),
  ),
)

ftp://anonymous@ftp.example.com/pub/test.jpg
array (
  'scheme' => 'ftp',
  'host' => 'ftp.example.com',
  'user' => 'anonymous',
  'path' => '/pub/test.jpg',
  'tld' => 'com',
  'dirname' => '/pub',
  'basename' => 'test.jpg',
  'extension' => 'jpg',
  'filename' => 'test',
)

file:///home/user/.config/test.config
array (
  'scheme' => 'file',
  'path' => '/home/user/.config/test.config',
  'dirname' => '/home/user/.config',
  'basename' => 'test.config',
  'extension' => 'config',
  'filename' => 'test',
)

chrome://settings/passwords
array (
  'scheme' => 'chrome',
  'host' => 'settings',
  'path' => '/passwords',
  'dirname' => '/',
  'basename' => 'passwords',
  'filename' => 'passwords',
)