是否有一种方法可以urlencode除路径中的目录分隔符/之外的内容?
例如:
urlencode('/this/is/my/file right here.jpg');
您可以使用:
explode
将路径分割成路径段,array_map
对每个项目应用rawurlencode
(不要使用urlencode
,那只针对于application/x-www-form-urlencoded编码的查询参数!),以及implode
来重新组合这些路径段。因此,所有操作可以放在一行内:
$path = implode('/', array_map('rawurlencode', explode('/', $path)));
再次替换它们:
str_replace('%2F', '/', urlencode('/this/is/my/file right here.jpg'));
请注意,如果您要将结果作为查询字符串传递,则不应执行上面的替换操作 - 仅使用urlencode
。如果在路径部分中使用它,则应改用rawurlencode。
str_replace("%2F","/",urlencode('/this/is/my/file right here.jpg'));
$array = explode('/', '/this/is/my/file right here.jpg');
foreach ($array as &$value) {
$value = urlencode($value);
}
print implode('/', $array);
str_replace
更简单。无论哪种方式,都要加1个赞给rawurlencode
;它总是正确的选择,而urlencode
有时会出错。 - bobince