URI Builders

new Uri\Rfc3986\UriBuilder(); UriBuilder::setScheme/setHost/setPort/setPath/setQuery/setFragment(...): static; UriBuilder::build(?Uri\Rfc3986\Uri $baseUrl = null): Uri\Rfc3986\Uri; new Uri\WhatWg\UrlBuilder(); url_percent_encode(string $input, Uri\WhatWg\UrlPercentEncodingMode $mode): string

The PHP 8.6 URI builder family: UriBuilder stores only overrides and build() rebases onto an existing URI — completing the parse↔build pair with parse_url/http_build_query; the coexistence of RFC 3986 and WHATWG is the teaching core.

C C23

C23
#include <stdio.h>

int main(void) {
    /* no standard URL builder in C: parts become format arguments and
       encoding is on you (curl_url_* is the de-facto library) */
    char uri[128] = {0};
    snprintf(uri, sizeof uri, "%s://%s%s?%s", "https", "php.net", "/releases/8.6", "lang=zh");
    printf("%s\n", uri);
    snprintf(uri, sizeof uri, "%s://%s%s?%s", "http", "example.com", "/new", "y=2");
    printf("%s\n", uri);
    return 0;
}
Output
https://php.net/releases/8.6?lang=zh
http://example.com/new?y=2

C++ C++26

C++26
#include <iostream>
#include <string>

// std has no URI class; a tiny encoder shows what builders do for you
static std::string encode_path(const std::string &s) {
    static const char *hex = "0123456789ABCDEF";
    std::string out;
    for (char c : s) {
        unsigned char b = static_cast<unsigned char>(c);
        bool safe = (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '0' && b <= '9')
            || b == '-' || b == '.' || b == '_' || b == '~' || b == '/';
        if (safe) {
            out += static_cast<char>(b);
        } else {
            out += '%';
            out += hex[b >> 4];
            out += hex[b & 0xF];
        }
    }
    return out;
}

int main() {
    std::string uri = std::string("https") + "://" + "php.net" + encode_path("/releases/8.6") + "?" + "lang=zh";
    std::cout << uri << '\n';
    std::cout << encode_path("/a b") << '\n';
    return 0;
}
Output
https://php.net/releases/8.6?lang=zh
/a%20b

C# v11.0.100

v11.0.100
using System;

// System.UriBuilder is .NET's same-named counterpart
var b = new UriBuilder("https", "php.net");
b.Path = "/releases/8.6";
b.Query = "lang=zh";
Console.WriteLine(b.Uri.ToString());

var u = new Uri("http://example.com/old?x=1");
Console.WriteLine(new Uri(u, "/new?y=2").ToString());
Output
https://php.net/releases/8.6?lang=zh
http://example.com/new?y=2

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"net/url"
)

func main() {
	// url.URL is a struct of parts; String() assembles it
	u := url.URL{Scheme: "https", Host: "php.net", Path: "/releases/8.6", RawQuery: "lang=zh"}
	fmt.Println(u.String())

	base, _ := url.Parse("http://example.com/old?x=1")
	base.Path = "/new"
	base.RawQuery = "y=2"
	fmt.Println(base.String())

	fmt.Println(url.Values{"q": {"hello world"}}.Encode())
}
Output
https://php.net/releases/8.6?lang=zh
http://example.com/new?y=2
q=hello+world

Java v27.0.1

v27.0.1
import java.net.URI;

public class Main {
    public static void main(String[] args) throws Exception {
        // the 5-arg constructor percent-encodes illegal characters itself
        URI uri = new URI("https", "php.net", "/releases/8.6", "lang=zh", null);
        System.out.println(uri.toString());
        System.out.println(uri.getScheme() + " " + uri.getHost() + " " + uri.getPath());

        URI base = URI.create("http://example.com/old?x=1");
        System.out.println(base.resolve("/new?y=2").toString());
    }
}
Output
https://php.net/releases/8.6?lang=zh
https php.net /releases/8.6
http://example.com/new?y=2

JavaScript v26.13.1

v26.13.1
// WHATWG URL is native to the runtime — the same standard as Uri\WhatWg
const u = new URL("https://php.net");
u.pathname = "/releases/8.6";
u.search = "?lang=zh";
console.log(u.toString());
console.log(`${u.protocol} ${u.host} ${u.pathname}`);

// spaces become %20 per the WHATWG path percent-encode set
const w = new URL("https://example.com/a b?q=hello world");
console.log(w.toString());

// URLSearchParams uses application/x-www-form-urlencoded: space -> +
console.log(new URLSearchParams({q: "hello world"}).toString());
Output
https://php.net/releases/8.6?lang=zh
https: php.net /releases/8.6
https://example.com/a%20b?q=hello%20world
q=hello+world

PHP v8.6.0

v8.6.0
// RFC 3986 builder: set components, then assemble
$b = new Uri\Rfc3986\UriBuilder();
$b->setScheme('https')->setHost('php.net')->setPath('/releases/8.6')->setQuery('lang=zh');
$uri = $b->build();
var_dump($uri->toString());
var_dump($uri->getScheme(), $uri->getHost(), $uri->getPath());

// build() rebases onto an existing URI: the builder stores only overrides
$base = Uri\Rfc3986\Uri::parse('http://example.com/old?x=1');
$b2 = new Uri\Rfc3986\UriBuilder();
$b2->setPath('/new')->setQuery('y=2');
var_dump($b2->build($base)->toString());

// WHATWG builder: percent-encodes per the browser URL standard
$wb = new Uri\WhatWg\UrlBuilder();
$wb->setScheme('https')->setHost('example.com')->setPath('/a b')->setQuery('q=hello world');
var_dump($wb->build()->toAsciiString());

// explicit percent-encoding, mode picks the safe-character set
var_dump(Uri\WhatWg\url_percent_encode('hello world', Uri\WhatWg\UrlPercentEncodingMode::Path));
var_dump(Uri\WhatWg\url_percent_encode('a=b&c=d', Uri\WhatWg\UrlPercentEncodingMode::Query));
Output
string(36) "https://php.net/releases/8.6?lang=zh"
string(5) "https"
string(7) "php.net"
string(13) "/releases/8.6"
string(26) "http://example.com/new?y=2"
string(41) "https://example.com/a%20b?q=hello%20world"
string(13) "hello%20world"
string(7) "a=b&c=d"

Python v3.15.2

v3.15.2
from urllib.parse import urlencode, urlparse, urlunparse

# urlunparse reassembles a six-tuple: the urllib.parse builder half
print(urlunparse(("https", "php.net", "/releases/8.6", "", "lang=zh", "")))

scheme, netloc, path, params, query, fragment = urlparse("http://example.com/old?x=1")
print(urlunparse((scheme, netloc, "/new", params, "y=2", fragment)))

print(urlencode({"q": "hello world"}))
Output
https://php.net/releases/8.6?lang=zh
http://example.com/new?y=2
q=hello+world

Rust v1.99.1

v1.99.1
fn percent_encode_path(s: &str) -> String {
    let mut out = String::new();
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => {
                out.push(b as char);
            }
            _ => out.push_str(&format!("%{:02X}", b)),
        }
    }
    out
}

fn main() {
    // std has no URI builder; real projects reach for the `url` crate
    let uri = format!("{}://{}{}?{}", "https", "php.net", percent_encode_path("/releases/8.6"), "lang=zh");
    println!("{}", uri);
    println!("{}", percent_encode_path("/a b"));
}
Output
https://php.net/releases/8.6?lang=zh
/a%20b

TypeScript v26.13.1

v26.13.1
// WHATWG URL is native to the runtime — the same standard as Uri\WhatWg
const u = new URL("https://php.net");
u.pathname = "/releases/8.6";
u.search = "?lang=zh";
console.log(u.toString());
console.log(`${u.protocol} ${u.host} ${u.pathname}`);

const w = new URL("https://example.com/a b?q=hello world");
console.log(w.toString());

console.log(new URLSearchParams({q: "hello world"}).toString());
Output
https://php.net/releases/8.6?lang=zh
https: php.net /releases/8.6
https://example.com/a%20b?q=hello%20world
q=hello+world

Language differences

C: no standard builder (example): snprintf string assembly is the norm and encoding is on you; the de-facto standard is libcurl's curl_url_* API (set parts + get URL) — same component-wise idea as UriBuilder, but with manual storage management.

C++: nothing in std (example): a hand-written encoder demonstrates what builders do for you — the safe-character-set test plus percent hex-encoding; Poco::Net URI or cpp-httplib are the ecosystem counterparts, and the standard library remains empty through C++26.

C#: System.UriBuilder (example): .NET's same-named counterpart — constructor/properties set parts, the Uri property yields the product; new Uri(base, relative) mirrors the rebasing semantics of build(baseUrl); System.Uri follows RFC 3986 style while keeping Windows path-compatibility details.

Go: the net/url.URL struct (example): parts as fields, String() assembles, url.Values.Encode() emits form-encoded queries (space → +, against WHATWG's path %20); URL.Parse plus field overrides is Go's "base plus overrides" style.

Java: java.net.URI (example): the 5-arg constructor percent-encodes illegal characters itself and resolve() does relative resolution; strict RFC 2396/3986 lineage with no tolerance for WHATWG's browser grammar (an unencoded space throws) — the two-standard war is a single choice on the Java side.

JavaScript: URL + URLSearchParams (example): the WHATWG URL is native to the runtime — the same standard as Uri\WhatWg; URL instance properties are writable (assignment re-encodes), and URLSearchParams speaks application/x-www-form-urlencoded (space → +) while the path encodes space as %20 — one URL, two space rules: the live textbook of "two encoding sets".

PHP: the 8.6 ext/uri builder family (example): Uri\Rfc3986\UriBuilder and Uri\WhatWg\UrlBuilder run as twin tracks — RFC 3986 (strict document grammar) versus WHATWG (the browser URL Living Standard): the industry really does have two standards, and PHP is one of few languages to make both first-class APIs; build(?Uri $baseUrl) stores only overrides and fills the rest from the base — completing the parse↔build pair with parse_url (parts out) and http_build_query (query string in); url_percent_encode(string, UrlPercentEncodingMode) exposes WHATWG's per-component encode sets (Path/Query/Fragment/FormQuery and more, ten modes), where Query leaves & and = untouched while space becomes %20 — a fixed assertion verified by running it.

Python: urllib.parse.urlunparse (example): a six-tuple (scheme, netloc, path, params, query, fragment) in, URL string out — the official parse↔build pair with urlparse; urlencode emits form encoding (space → +), with no WHATWG per-component encode sets — single-track RFC style.

Rust: the url crate (example): std has no URI building (the example hand-writes percent_encode_path to show it), and the ecosystem standard is url::Url (the WHATWG spec in Rust — tolerant parse, auto-encoding set_path), with the percent-encoding crate supplying encode_sets (the counterpart of UrlPercentEncodingMode).

TypeScript: same as JS (example): lib.dom's URL/URLSearchParams types give every WHATWG part operation a compile-time signature; toString() output matches the runtime byte for byte.