我需要使用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。
有没有比这更优雅的解决方案了?还是这基本上是要走的路?
最佳答案
@deceze绝对让我走了正确的路,所以请投票支持他的答案。但是,这确实是有效的:
$encoded_url = preg_replace_callback('#://([^/]+)/([^?]+)#', function ($match) {
return '://' . $match[1] . '/' . join('/', array_map('rawurlencode', explode('/', $match[2])));
}, $unencoded_url);
有几件事要注意:
urlencode()
不是要走的路!您需要使用rawurlencode()
作为路径,以便将空格编码为%20
而不是+
。对于查询字符串,将空格编码为+
很好,但对于路径则不是那么热。