仅对URL的目录和文件名进行urlencode [英] urlencode only the directory and file names of a URL
问题描述
我需要使用PHP对URL的目录路径和文件名进行URL编码.
I need to URL encode just the directory path and file name of a URL using PHP.
所以我想对类似http://example.com/file name
的东西进行编码,并使其生成http://example.com/file%20name
.
So I want to encode something like http://example.com/file name
and have it result in http://example.com/file%20name
.
当然,如果我执行urlencode('http://example.com/file name');
,那么我最终会得到http%3A%2F%2Fexample.com%2Ffile+name
.
Of course, if I do urlencode('http://example.com/file name');
then I end up with http%3A%2F%2Fexample.com%2Ffile+name
.
一个明显的解决方案(无论如何对我来说)是使用parse_url()
将URL拆分为方案,主机等,然后仅urlencode()
需要路径的部分(如路径).然后,我将使用http_build_url()
重新组装URL.
The obvious (to me, anyway) solution is to use parse_url()
to split the URL into scheme, host, etc. and then just urlencode()
the parts that need it like the path. Then, I would reassemble the URL using http_build_url()
.
有没有比这更优雅的解决方案了?还是这基本上是要走的路?
Is there a more elegant solution than that? Or is that basically the way to go?
推荐答案
@deceze无疑使我走了正确的道路,所以请投票支持他的答案.但这确实是有效的:
@deceze definitely got me going down the right path, so go upvote his answer. But here is exactly what worked:
$encoded_url = preg_replace_callback('#://([^/]+)/([^?]+)#', function ($match) {
return '://' . $match[1] . '/' . join('/', array_map('rawurlencode', explode('/', $match[2])));
}, $unencoded_url);
有几件事要注意:
-
http_build_url需要安装PECL,因此如果您将代码分发给其他人(如本例所示),您可能希望避免使用它,并像我在此处那样坚持进行reg exp解析(从@deceze的网站大量窃取答案-再次,投票赞成该内容.)
http_build_url requires a PECL install so if you are distributing your code to others (as I am in this case) you might want to avoid it and stick with reg exp parsing like I did here (stealing heavily from @deceze's answer--again, go upvote that thing).
urlencode()
不是要走的路!您需要rawurlencode()
作为路径,以便空格被编码为%20
而不是+
.对于查询字符串,将空格编码为+
很好,但对于路径则不太适合.
urlencode()
is not the way to go! You need rawurlencode()
for the path so that spaces get encoded as %20
and not +
. Encoding spaces as +
is fine for query strings, but not so hot for paths.
这不适用于需要用户名/密码编码的URL.对于我的用例,我认为我并不在乎这些,因此我并不担心.但是,如果您的用例在这方面有所不同,则需要注意这一点.
This won't work for URLs that need a username/password encoded. For my use case, I don't think I care about those, so I'm not worried. But if your use case is different in that regard, you'll need to take care of that.
这篇关于仅对URL的目录和文件名进行urlencode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!