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

Winston Smith picture Winston Smith · Jun 19, 2013 · Viewed 8.7k times · Source
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 ?

Answer

ducin picture ducin · Jun 19, 2013

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.