Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

urlencode only the directory and file names of a URL

Tags:

php

urlencode

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?

like image 454
Trott Avatar asked Nov 01 '11 22:11

Trott


1 Answers

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)

like image 174
deceze Avatar answered Oct 07 '22 14:10

deceze