仅对 URL 的目录名和文件名进行 urlencode

发布于 2024-12-13 07:49:25 字数 498 浏览 0 评论 0原文

我需要使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

御弟哥哥 2024-12-20 07:49:25

@deceze 绝对让我走上了正确的道路,所以去投票他的答案。但这正是有效的方法:

    $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 的答案中大量窃取 - 再次投票)。

  • urlencode() 不是正确的方法!您需要 rawurlencode() 作为路径,以便空格被编码为 %20 而不是 +。将空格编码为 + 对于查询字符串来说很好,但对于路径来说就不那么热了。

  • 这不适用于需要用户名/密码编码的 URL。对于我的用例,我认为我不关心这些,所以我不担心。但如果您的用例在这方面有所不同,您就需要注意这一点。

@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);

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 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.

  • 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.

若沐 2024-12-20 07:49:25

正如你所说,沿着这些思路的事情应该做到这一点:

$parts = parse_url($url);
if (!empty($parts['path'])) {
    $parts['path'] = join('/', array_map('rawurlencode', explode('/', $parts['path'])));
}
$url = http_build_url($parts);

或者可能:(

$url = preg_replace_callback('#https?://.+/([^?]+)#', function ($match) {
           return join('/', array_map('rawurlencode', explode('/', $match[1])));
       }, $url);

正则表达式尚未完全测试)

As you say, something along these lines should do it:

$parts = parse_url($url);
if (!empty($parts['path'])) {
    $parts['path'] = join('/', array_map('rawurlencode', explode('/', $parts['path'])));
}
$url = http_build_url($parts);

Or possibly:

$url = preg_replace_callback('#https?://.+/([^?]+)#', function ($match) {
           return join('/', array_map('rawurlencode', explode('/', $match[1])));
       }, $url);

(Regex not fully tested though)

屋顶上的小猫咪 2024-12-20 07:49:25
function encode_uri($url){
    $exp = "{[^0-9a-z_.!~*'();,/?:@&=+$#%\[\]-]}i";
    return preg_replace_callback($exp, function($m){
        return sprintf('%%%02X',ord($m[0]));
    }, $url);
}
function encode_uri($url){
    $exp = "{[^0-9a-z_.!~*'();,/?:@&=+$#%\[\]-]}i";
    return preg_replace_callback($exp, function($m){
        return sprintf('%%%02X',ord($m[0]));
    }, $url);
}
别再吹冷风 2024-12-20 07:49:25

更简单:

$encoded = implode("/", array_map("rawurlencode", explode("/", $path)));

Much simpler:

$encoded = implode("/", array_map("rawurlencode", explode("/", $path)));
ゞ花落谁相伴 2024-12-20 07:49:25

我觉得这个功能还可以:

function newUrlEncode ($url) {
    return str_replace(array('%3A', '%2F'), '/', urlencode($url));
}

I think this function ok:

function newUrlEncode ($url) {
    return str_replace(array('%3A', '%2F'), '/', urlencode($url));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文