php中文url转码
封面图
•
2025-09-30
•
PHP
175
0
0
0
在 PHP 中处理 **中文 URL 转码**(即对 URL 进行编码,使中文字符可以安全地出现在 URL 中),通常使用 `urlencode()` 或 `rawurlencode()` 函数。 --- ## ✅ 1. 使用 `urlencode()` ```php $url = "https://example.com/中文"; $encoded_url = urlencode($url); echo $encoded_url; ``` **输出:** ``` https%3A%2F%2Fexample.com%2F%E4%B8%AD%E6%96%87 ``` > 注意:`urlencode()` 会将空格转为 `+`,而 `rawurlencode()` 会将空格转为 `%20`。 --- ## ✅ 2. 使用 `rawurlencode()` ```php $url = "https://example.com/中文"; $encoded_url = rawurlencode($url); echo $encoded_url; ``` **输出:** ``` https%3A%2F%2Fexample.com%2F%E4%B8%AD%E6%96%87 ``` > 更推荐使用 `rawurlencode()`,因为它是 RFC 3986 标准中定义的 URL 编码方式,适用于现代浏览器和 API 接口。 --- ## ✅ 3. 对 URL 中的某个参数进行编码 如果你只需要对 URL 的某个参数(如 `?name=中文`)进行编码: ```php $name = "中文"; $encoded_name = rawurlencode($name); echo "https://example.com?name=" . $encoded_name; ``` **输出:** ``` https://example.com?name=%E4%B8%AD%E6%96%87 ``` --- ## ✅ 4. 解码 URL(反向操作) 如果需要解码: ```php $encoded_url = "https%3A%2F%2Fexample.com%2F%E4%B8%AD%E6%96%87"; $decoded_url = rawurldecode($encoded_url); echo $decoded_url; // 输出: https://example.com/中文 ``` --- ## 📌 小贴士 | 函数 | 空格处理 | 适用场景 | |--------------|----------|------------------------| | `urlencode()` | `+` | 旧式表单提交 | | `rawurlencode()` | `%20` | 现代 URL 编码、API 请求 | --- 如果你有具体的 URL 示例或使用场景,我可以帮你更精准地处理。欢迎继续提问!
上一篇:
PHP计算字符串长度
下一篇:
面试问题 除了本公司外,还应聘了哪些公司?
标题录入,一次不能超过6条
返回顶部
留言
留言
评论