PHP URL函数

PHP rawurlencode() 函数根据 RFC 3986 对给定字符串进行编码。该函数返回一个字符串,其中所有非除 -_.~ 之外的字母数字字符替换为百分号 (%) 后跟两个十六进制数字。

来自 RFC 3986:统一资源标识符 (URI) 是标识抽象或物理资源的紧凑字符序列。本规范定义了通用 URI 语法和解析可能采用相对形式的 URI 引用的过程,以及在 Internet 上使用 URI 的指南和安全注意事项。 

URI 语法定义了一个语法,它是所有有效 URI 的超集,允许实现解析 URI 引用的公共组件,而无需知道每个可能标识符的特定于方案的要求。

语法

rawurlencode(string) 

参数

string必填。 指定要编码的 URL。

返回值

返回一个字符串,其中除-_.~ 已替换为百分号 (%) 后跟两个十六进制数字。这是 RFC 3986 中描述的编码,用于保护文字字符不被解释为特殊 URL 分隔符,并保护 URL 不被带有字符转换的传输媒体(如某些电子邮件系统)破坏。

示例:

下面的示例显示了 rawurlencode() 函数的用法。

<?php
echo '<a href="www.yxjc123.com/',
  rawurlencode('an online learning portal'), '">';
?> 

上述代码的输出将是:

<a href="www.yxjc123.com/an%20online%20learning%20portal"> 

示例:

再考虑一个示例,它显示了字符串的编码方式以及解码。

<?php
$str1 = "Yxjc123 an online learning portal";
$encoded_str1 = rawurlencode($str1);

echo "The string is: $str1 \n";
echo "Encoded string: $encoded_str1 \n";

$str2 = "Yxjc123%20an%20online%20learning%20portal";
$decoded_str2 = rawurldecode($str2);

echo "\nThe string is: $str2 \n";
echo "Decoded string: $decoded_str2 \n";
?> 

上述代码的输出将是:

The string is: Yxjc123 an online learning portal 
Encoded string: Yxjc123%20an%20online%20learning%20portal 

The string is: Yxjc123%20an%20online%20learning%20portal 
Decoded string: Yxjc123 an online learning portal