PHP urlencode - encode only the filename and dont touch the slashes

放肆的年华 提交于 2020-06-11 20:06:15

问题


http://www.example.com/some_folder/some file [that] needs "to" be (encoded).zip
urlencode($myurl);

The problem is that urlencode will also encode the slashes which makes the URL unusable. How can i encode just the last filename ?


回答1:


Try this:

$str = 'http://www.example.com/some_folder/some file [that] needs "to" be (encoded).zip';
$pos = strrpos($str, '/') + 1;
$result = substr($str, 0, $pos) . urlencode(substr($str, $pos));

You're looking for the last occurrence of the slash sign. The part before it is ok so just copy that. And urlencode the rest.




回答2:


First of all, here's why you should be using rawurlencode instead of urlencode.

To answer your question, instead of searching for a needle in a haystack and risking not encoding other possible special characters in your URL, just encode the whole thing and then fix the slashes (and colon).

<?php
$myurl = 'http://www.example.com/some_folder/some file [that] needs "to" be (encoded).zip';
$myurl = rawurlencode($myurl);
$myurl = str_replace('%3A',':',str_replace('%2F','/',$myurl));

Results in this:

http://www.example.com/some_folder/some%20file%20%5Bthat%5D%20needs%20%22to%22%20be%20%28encoded%29.zip




回答3:


Pull the filename off and escape it.

$temp = explode('/', $myurl);
$filename = array_pop($temp);

$newFileName = urlencode($filename);

$myNewUrl = implode('/', array_push($newFileName));


来源:https://stackoverflow.com/questions/17179877/php-urlencode-encode-only-the-filename-and-dont-touch-the-slashes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!