仅对 URL 的目录名和文件名进行 urlencode
我需要使用 PHP 对 URL 的目录路径和文件名进行 URL 编码。
因此,我想对诸如 http://example.com/file name
之类的内容进行编码,并使其结果为 http://example.com/file%20name
。
当然,如果我这样做 urlencode('http://example.com/file name');
那么我最终会得到 http%3A%2F%2Fexample.com%2Ffile+name
。
显而易见的(无论如何对我来说)解决方案是使用 parse_url()
将 URL 拆分为方案、主机等,然后只使用 urlencode()
需要的部分它喜欢这条路。然后,我将使用 http_build_url()
重新组装 URL。
还有比这更优雅的解决方案吗?或者这基本上就是要走的路吗?
I need to URL encode just the directory path and file name of a URL using PHP.
So I want to encode something like http://example.com/file name
and have it result in http://example.com/file%20name
.
Of course, if I do urlencode('http://example.com/file name');
then I end up with http%3A%2F%2Fexample.com%2Ffile+name
.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
@deceze 绝对让我走上了正确的道路,所以去投票他的答案。但这正是有效的方法:
有几点需要注意:
http_build_url 需要安装 PECL,因此如果您将代码分发给其他人(就像我在本例中一样),您可能需要避免它并坚持使用 reg exp 解析就像我在这里所做的那样(从 @deceze 的答案中大量窃取 - 再次投票)。
urlencode()
不是正确的方法!您需要rawurlencode()
作为路径,以便空格被编码为%20
而不是+
。将空格编码为+
对于查询字符串来说很好,但对于路径来说就不那么热了。这不适用于需要用户名/密码编码的 URL。对于我的用例,我认为我不关心这些,所以我不担心。但如果您的用例在这方面有所不同,您就需要注意这一点。
@deceze definitely got me going down the right path, so go upvote his answer. But here is exactly what worked:
There are a few things to note:
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()
is not the way to go! You needrawurlencode()
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.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.
正如你所说,沿着这些思路的事情应该做到这一点:
或者可能:(
正则表达式尚未完全测试)
As you say, something along these lines should do it:
Or possibly:
(Regex not fully tested though)
更简单:
Much simpler:
我觉得这个功能还可以:
I think this function ok: