urlencode only the directory and file names of a URL

后端 未结 5 1758
生来不讨喜
生来不讨喜 2021-02-20 08:18

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 r

相关标签:
5条回答
  • 2021-02-20 08:46
    function encode_uri($url){
        $exp = "{[^0-9a-z_.!~*'();,/?:@&=+$#%\[\]-]}i";
        return preg_replace_callback($exp, function($m){
            return sprintf('%%%02X',ord($m[0]));
        }, $url);
    }
    
    0 讨论(0)
  • 2021-02-20 08:50

    Much simpler:

    $encoded = implode("/", array_map("rawurlencode", explode("/", $path)));
    
    0 讨论(0)
  • 2021-02-20 08:53

    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)

    0 讨论(0)
  • 2021-02-20 08:58

    I think this function ok:

    function newUrlEncode ($url) {
        return str_replace(array('%3A', '%2F'), '/', urlencode($url));
    }
    
    0 讨论(0)
  • 2021-02-20 09:02

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

    0 讨论(0)
提交回复
热议问题