URL 函数
PHP Manual

urlencode

(PHP 4, PHP 5)

urlencode编码 URL 字符串

说明

string urlencode ( string $str )

返回字符串,此字符串中除了 -_. 之外的所有非字母数字字符都将被替换成百分号(%)后跟两位十六进制数,空格则编码为加号(+)。此编码与 WWW 表单 POST 数据的编码方式是一样的,同时与 application/x-www-form-urlencoded 的媒体类型编码方式一样。由于历史原因,此编码在将空格编码为加号(+)方面与 RFC1738 编码(参见 rawurlencode())不同。此函数便于将字符串编码并将其用于 URL 的请求部分,同时它还便于将变量传递给下一页:

Example #1 urlencode() 例子

<?php
echo '<a href="mycgi?foo='urlencode($userinput), '">';
?>

注意:小心与 HTML 实体相匹配的变量。像 &amp、&copy 和 &pound 都将被浏览器解析,并使用实际实体替代所期待的变量名。这是明显的混乱,W3C 已经告诫人们好几年了。参考地址:» http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.2。PHP 通过 arg_separator.ini 指令,支持将参数分割符变成 W3C 所建议的分号。不幸的是大多数用户代理并不发送分号分隔符格式的表单数据。较为简单的解决办法是使用 &amp; 代替 & 作为分隔符。你不需要为此修改 PHP 的 arg_separator。让它仍为 &,而仅使用 htmlentities()htmlspecialchars() 对你的 URL 进行编码。

Example #2 urlencode()htmlentities() 例子

<?php
$query_string 
'foo=' urlencode($foo) . '&bar=' urlencode($bar);
echo 
'<a href="mycgi?' htmlentities($query_string) . '">';
?>

参见 urldecode()htmlentities()rawurldecode()rawurlencode()

参数

str

The string to be encoded.

返回值

Returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+) signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in application/x-www-form-urlencoded media type. This differs from the » RFC 3986 encoding (see rawurlencode()) in that for historical reasons, spaces are encoded as plus (+) signs.

范例

Example #3 urlencode() example

<?php
echo '<a href="mycgi?foo='urlencode($userinput), '">';
?>

Example #4 urlencode() and htmlentities() example

<?php
$query_string 
'foo=' urlencode($foo) . '&bar=' urlencode($bar);
echo 
'<a href="mycgi?' htmlentities($query_string) . '">';
?>

注释

Note:

Be careful about variables that may match HTML entities. Things like &amp, &copy and &pound are parsed by the browser and the actual entity is used instead of the desired variable name. This is an obvious hassle that the W3C has been telling people about for years. The reference is here: » http://www.w3.org/TR/html4/appendix/notes.html#h-B.2.2.

PHP supports changing the argument separator to the W3C-suggested semi-colon through the arg_separator .ini directive. Unfortunately most user agents do not send form data in this semi-colon separated format. A more portable way around this is to use &amp; instead of & as the separator. You don't need to change PHP's arg_separator for this. Leave it as &, but simply encode your URLs using htmlentities() or htmlspecialchars().

参见


URL 函数
PHP Manual