Parse URL

PHP String Function: Parse URL

parse_str(): Parses the string into variables

PHP 4, PHP 5, PHP 7, PHP 8

<?php
parse_str(string $string, array &$result): void

$str = "first=value&arr[]=foo+bar&arr[]=baz";

// Recommended
parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

// DISCOURAGED
parse_str($str);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

http_build_query(): Generate URL-encoded query string

PHP 5, PHP 7, PHP 8

http_build_query(
    array|object $data,
    string $numeric_prefix = "",
    ?string $arg_separator = null,
    int $encoding_type = PHP_QUERY_RFC1738
): string
$data = array('foo', 'bar', 'baz', null, 'boom', 'cow' => 'milk', 'php' => 'hypertext processor');

echo http_build_query($data) . "\n";
echo http_build_query($data, 'myvar_');

// 0=foo&1=bar&2=baz&4=boom&cow=milk&php=hypertext+processor
// myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_4=boom&cow=milk&php=hypertext+processor
$data = array(
    'user' => array(
        'name' => 'Bob Smith',
        'age'  => 47,
        'sex'  => 'M',
        'dob'  => '5/12/1956'
    ),
    'pastimes' => array('golf', 'opera', 'poker', 'rap'),
    'children' => array(
        'bobby' => array('age'=>12, 'sex'=>'M'),
        'sally' => array('age'=>8, 'sex'=>'F')
    ),
    'CEO'
);

echo http_build_query($data, 'flags_');

// user%5Bname%5D=Bob+Smith&user%5Bage%5D=47&user%5Bsex%5D=M&
// user%5Bdob%5D=5%2F12%2F1956&pastimes%5B0%5D=golf&pastimes%5B1%5D=opera&
// pastimes%5B2%5D=poker&pastimes%5B3%5D=rap&children%5Bbobby%5D%5Bage%5D=12&
// children%5Bbobby%5D%5Bsex%5D=M&children%5Bsally%5D%5Bage%5D=8&
// children%5Bsally%5D%5Bsex%5D=F&flags_0=CEO

parse_url()

parse_url(string $url, int $component = -1): int|string|array|null|false

Parse a URL and return its components

$url = 'http://username:password@hostname:9090/path?arg=value#anchor';

var_dump(parse_url($url));
// array(8) {
//   ["scheme"]=>
//   string(4) "http"
//   ["host"]=>
//   string(8) "hostname"
//   ["port"]=>
//   int(9090)
//   ["user"]=>
//   string(8) "username"
//   ["pass"]=>
//   string(8) "password"
//   ["path"]=>
//   string(5) "/path"
//   ["query"]=>
//   string(9) "arg=value"
//   ["fragment"]=>
//   string(6) "anchor"
// }
var_dump(parse_url($url, PHP_URL_SCHEME));
// string(4) "http"

var_dump(parse_url($url, PHP_URL_USER));
// string(8) "username"

var_dump(parse_url($url, PHP_URL_PASS));
// string(8) "password"

var_dump(parse_url($url, PHP_URL_HOST));
// string(8) "hostname"

var_dump(parse_url($url, PHP_URL_PORT));
// int(9090)

var_dump(parse_url($url, PHP_URL_PATH));
// string(5) "/path"

var_dump(parse_url($url, PHP_URL_QUERY));
// string(9) "arg=value"

var_dump(parse_url($url, PHP_URL_FRAGMENT));
// string(6) "anchor"

Reference