urlencode
urlencode(string $string): string
按 application/x-www-form-urlencoded 规则编码字符串(空格转为加号,其余非安全字符转 %XX)。
C C23
C23
#include <ctype.h>
#include <stdio.h>
int main(void) {
const char *s = "a b c!";
char out[64];
int j = 0;
for (int i = 0; s[i] != '\0'; i++) {
unsigned char ch = (unsigned char)s[i];
if (isalnum(ch) || ch == '-' || ch == '_' || ch == '.') {
out[j++] = (char)ch;
} else {
j += sprintf(out + j, "%%%02X", ch);
}
}
out[j] = '\0';
printf("%s\n", out);
return 0;
}
输出
a%20b%20c%21
C++ C++26
C++26
#include <cctype>
#include <iostream>
#include <string>
int main() {
std::string s = "a b c!";
std::string out;
char buf[4];
for (unsigned char ch : s) {
if (std::isalnum(ch) || ch == '-' || ch == '_' || ch == '.') {
out += (char)ch;
} else {
snprintf(buf, sizeof(buf), "%%%02X", ch);
out += buf;
}
}
std::cout << out << "\n";
return 0;
}
输出
a%20b%20c%21
C# v11.0.100
v11.0.100
Console.WriteLine(Uri.EscapeDataString("a b c!"));
输出
a%20b%20c%21
Go v1.27.4
v1.27.4
package main
import (
"fmt"
"net/url"
)
func main() {
fmt.Println(url.QueryEscape("a b c!"))
}
输出
a+b+c%21
Java v27.0.1
v27.0.1
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String[] args) {
System.out.println(URLEncoder.encode("a b c!", StandardCharsets.UTF_8));
}
}
输出
a+b+c%21
JavaScript v26.13.1
v26.13.1
console.log(encodeURIComponent("a b c!"));
输出
a%20b%20c!
PHP v8.6.0
v8.6.0
echo urlencode("a b c!");
输出
a+b+c%21
Python v3.15.2
v3.15.2
from urllib.parse import quote, quote_plus
s = "a b c!"
print(quote(s), quote_plus(s))
输出
a%20b%20c%21 a+b+c%21
Rust v1.99.1
v1.99.1
fn main() {
let s = "a b c!";
let mut out = String::new();
for b in s.bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.') {
out.push(b as char);
} else {
out.push_str(&format!("%{:02X}", b));
}
}
println!("{}", out);
}
输出
a%20b%20c%21
TypeScript v26.13.1
v26.13.1
const input: string = "a b c!";
console.log(encodeURIComponent(input));
输出
a%20b%20c!
语言差异说明
C:手写实现取 %20 口径(保留字母数字与 -_.,无第三方依赖);注意 isalnum 受 locale 影响的坑(传 unsigned char 转换后使用)。
C++:手写实现取 %20 口径。
C#:路径口径(空格→%20,RFC 3986):Uri.EscapeDataString。
Go:表单/query 口径(空格→+,RFC 1738/HTML 表单):url.QueryEscape;还会额外保留 */_-.。
Java:表单口径 URLEncoder.encode;还会额外保留 */_-.。
JavaScript:路径口径 encodeURIComponent(本例演示);输出 a%20b%20c! 是全表唯一差异:保留集额外放行 ! ~ * ' ( ),比 RFC 3986 unreserved 更宽,需要严格口径时得手工补编码这六个字符。
PHP:+ 号与 %20 是 URL 编码两大口径的分水岭——表单/query 口径(空格→+,RFC 1738/HTML 表单):urlencode;路径口径(空格→%20,RFC 3986):rawurlencode;混用口径的经典 bug:a+b 在 + 口径解码为 a b,在 %20 口径下 + 原样保留。
Python:表单口径 quote_plus;路径口径 quote(默认 safe='/' 保留斜杠)。
Rust:手写实现取 %20 口径。
TypeScript:同 JS,encodeURIComponent。