当前位置:首页 > PHP

php 实现urlencode

2026-02-28 12:02:31PHP

使用 urlencode 函数

PHP 提供了内置的 urlencode 函数,用于对字符串进行 URL 编码。该函数会将字符串中的非字母数字字符转换为 % 后跟两位十六进制数的形式,空格会被转换为 +

$string = "Hello World!";
$encoded = urlencode($string);
echo $encoded; // 输出: Hello+World%21

使用 rawurlencode 函数

rawurlencode 函数与 urlencode 类似,但会将空格编码为 %20 而不是 +,符合 RFC 3986 标准。

$string = "Hello World!";
$encoded = rawurlencode($string);
echo $encoded; // 输出: Hello%20World%21

编码查询参数

在构建 URL 查询字符串时,通常需要对参数名和参数值分别进行编码。

$params = [
    'name' => 'John Doe',
    'age' => 30,
    'city' => 'New York'
];

$query = http_build_query($params);
echo $query; // 输出: name=John+Doe&age=30&city=New+York

编码整个 URL

如果需要编码整个 URL,可以使用 urlencoderawurlencode 结合 parse_url 函数。

$url = "https://example.com/search?q=PHP URL encoding";
$parsed = parse_url($url);

$scheme = $parsed['scheme'];
$host = $parsed['host'];
$path = $parsed['path'];
$query = rawurlencode($parsed['query']);

$encodedUrl = "$scheme://$host$path?$query";
echo $encodedUrl; // 输出: https://example.com/search?q=PHP%20URL%20encoding

解码 URL

使用 urldecoderawurldecode 函数可以解码 URL 编码的字符串。

$encoded = "Hello+World%21";
$decoded = urldecode($encoded);
echo $decoded; // 输出: Hello World!

$encoded = "Hello%20World%21";
$decoded = rawurldecode($encoded);
echo $decoded; // 输出: Hello World!

注意事项

  • urlencoderawurlencode 不会编码 -, _, . 等字符。
  • 在编码路径部分时,建议使用 rawurlencode 以避免 + 被误解为空格。
  • 在编码查询参数时,http_build_query 会自动处理编码问题。

php 实现urlencode

标签: phpurlencode
分享给朋友:

相关文章

php 实现登录

php 实现登录

PHP 登录功能实现 使用 PHP 实现登录功能通常需要结合数据库验证和会话管理。以下是一个基本的登录实现流程: 数据库准备 创建用户表存储用户名和密码(建议使用哈希加密): CREATE TAB…

php 实现接口

php 实现接口

PHP 实现接口的方法 在 PHP 中,接口(Interface)用于定义一组方法的规范,而不包含具体的实现。类可以实现(implement)接口,并必须实现接口中定义的所有方法。 定义接口 接口…

php实现跳转

php实现跳转

PHP 实现页面跳转的方法 在 PHP 中实现页面跳转有多种方式,以下是常见的几种方法及其适用场景: 使用 header() 函数 通过 header() 函数发送 HTTP 头部信息实现跳转。注…

php实现下载

php实现下载

PHP实现文件下载 使用PHP实现文件下载可以通过设置HTTP头部信息强制浏览器下载文件而非直接打开。以下是几种常见的方法: 方法一:直接输出文件内容 $file_path = 'path/to/…

php 函数实现

php 函数实现

PHP 函数实现基础 PHP 函数的定义使用 function 关键字,后跟函数名和参数列表。函数名不区分大小写,但建议保持一致。 function functionName($param1, $p…

php 实现队列

php 实现队列

PHP 实现队列的方法 PHP 可以通过多种方式实现队列功能,以下是几种常见的实现方法: 使用数组实现队列 PHP 数组可以通过 array_push 和 array_shift 函数模拟队列的先进…