Break up/parse a URL into its constituent parts in php

江枫思渺然 提交于 2019-12-02 08:52:36

The best way is to combine the efforts of multiple builtin php functions such as parse_url (for the basic url parts), parse_str (for the query parameters) and pathinfo (for the directory, filename and extension parts).

parse_url

parse_url will parse the url and split it up into an associative array containing the following keys (if they are present in the url):

  • scheme (http, https, ftp, ...)
  • host (www.example.com)
  • port
  • user
  • pass
  • path (this will need further processing)
  • query (this will need further processing)
  • fragment (the anchor/hashbang part, anything after the hash mark)

parse_str

parse_str can be used to parse the query part from parse_url into a multidimensional (if needed) associative array.

pathinfo

pathinfo can be used to parse the path part from parse_url into an associative array which can contain the following keys:

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

Putting it all together

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;
}

Giving it a test

$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;
}

will yield these corresponding results:

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',
)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!