URI 构建器族

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

PHP 8.6 URI 构建器族:UriBuilder 只存覆盖项、build() 以既有 URI 为底座——与 parse_url/http_build_query 合成「解析 ↔ 构建」双向;RFC 3986 与 WHATWG 两套标准并存是本条的教学核心。

C C23

C23
#include <stdio.h>

int main(void) {
    /* C 没有标准 URL 构建器:部件变成格式参数,
       编码靠你自己(curl_url_* 是事实标准库) */
    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;
}
输出
https://php.net/releases/8.6?lang=zh
http://example.com/new?y=2

C++ C++26

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

// std 没有 URI 类;一个微型编码器展示构建器替你做了什么
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;
}
输出
https://php.net/releases/8.6?lang=zh
/a%20b

C# v11.0.100

v11.0.100
using System;

// System.UriBuilder 是 .NET 的同名对应物
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());
输出
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 是部件结构体;String() 负责组装
	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())
}
输出
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 {
        // 五参构造器自带百分号编码非法字符
        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());
    }
}
输出
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 是运行时原生——与 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}`);

// 空格按 WHATWG 路径百分号编码集变 %20
const w = new URL("https://example.com/a b?q=hello world");
console.log(w.toString());

// URLSearchParams 用 application/x-www-form-urlencoded:空格 -> +
console.log(new URLSearchParams({q: "hello world"}).toString());
输出
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 构建器:设部件,再组装
$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() 以既有 URI 为底座:构建器只存覆盖项
$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 构建器:按浏览器 URL 标准百分号编码
$wb = new Uri\WhatWg\UrlBuilder();
$wb->setScheme('https')->setHost('example.com')->setPath('/a b')->setQuery('q=hello world');
var_dump($wb->build()->toAsciiString());

// 显式百分号编码,mode 决定安全字符集
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));
输出
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 重组六元组:urllib.parse 的构建半边
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"}))
输出
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 没有 URI 构建器;真实项目会请出 `url` crate
    let uri = format!("{}://{}{}?{}", "https", "php.net", percent_encode_path("/releases/8.6"), "lang=zh");
    println!("{}", uri);
    println!("{}", percent_encode_path("/a b"));
}
输出
https://php.net/releases/8.6?lang=zh
/a%20b

TypeScript v26.13.1

v26.13.1
// WHATWG URL 是运行时原生——与 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());
输出
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

语言差异说明

C:无标准构建器(示例):snprintf 拼串是常态,编码责任全在人;事实标准是 libcurl 的 curl_url_* API(set parts + get URL),与 UriBuilder 的部件化思路一致但要手动管理存储。

C++:std 无 URI 类(示例):手写编码器演示构建器替你做的事——safe 字符集判定 + 百分号十六进制化;Poco::Net URI 或 cpp-httplib 是生态里的对应物,标准库直到 C++26 仍空缺。

C#:System.UriBuilder(示例):.NET 的同名对应物——构造器/属性设部件、Uri 属性取成品;new Uri(base, relative) 的相对解析与 build(baseUrl) 的底座语义同型;System.Uri 遵循 RFC 3986 风格但保留 Windows 路径兼容细节。

Go:net/url.URL 结构体(示例):部件直接做字段、String() 组装、url.Values.Encode() 生成表单编码查询(空格→+,对照 WHATWG 路径的 %20);URL.Parse + 字段覆盖是「底座+覆盖」的 Go 写法。

Java:java.net.URI(示例):五参构造器自带百分号编码(非法字符自动转义),resolve() 相对解析;严格 RFC 2396/3986 血统,不认 WHATWG 的浏览器宽容语法(如未编码空格直接抛异常)——两套标准之争在 Java 端是单选。

JavaScript:URL + URLSearchParams(示例):WHATWG URL 是语言运行时原生——与 Uri\WhatWg 同一标准;URL 实例部件属性可写(赋值即重编码),URLSearchParams 用 application/x-www-form-urlencoded(空格→+)而路径空格→%20——同一条 URL 两种空格,恰是「两套编码集」的活教材。

PHP:8.6 ext/uri 新增构建器族(示例):Uri\Rfc3986\UriBuilder 与 Uri\WhatWg\UrlBuilder 双轨并立——RFC 3986(严格文档语法)与 WHATWG(浏览器 URL Living Standard)业界真有两套,PHP 是少数把两者都做成一等 API 的语言;build(?Uri $baseUrl) 只存覆盖项、以底座补齐其余部件——与 parse_url(解析出部件)/http_build_query(构建查询串)合成解析↔构建双向;url_percent_encode(string, UrlPercentEncodingMode) 暴露 WHATWG 的分段编码集(Path/Query/Fragment/FormQuery 等十种 mode),Query 模式下 & 和 = 不转义而空格转 %20——实测固定断言。

Python:urllib.parse.urlunparse(示例):六元组 (scheme, netloc, path, params, query, fragment) 进、URL 串出——与 urlparse 构成官方解析↔构建对;urlencode 生成表单编码(空格→+),无 WHATWG 分段编码集概念,RFC 风格单轨。

Rust:url crate(示例):std 无 URI 构建(示例里手写 percent_encode_path 演示),生态标准是 url::Url(WHATWG 规范的 Rust 实现——parse 宽容、set_path 自动编码),另有无标准化的 percent-encoding crate 提供 encode_sets(与 UrlPercentEncodingMode 对应)。

TypeScript:同 JS(示例):lib.dom 的 URL/URLSearchParams 类型让 WHATWG 部件操作全部有编译期签名;tostring() 输出与运行时逐字节一致。