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 ?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With