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 ?
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:
Pull the filename off and escape it.
$temp = explode('/', $myurl);
$filename = array_pop($temp);
$newFileName = urlencode($filename);
$myNewUrl = implode('/', array_push($newFileName));
Similar to @Jeff Puckett's answer but as a function with arrays as replacements:
function urlencode_url($url) {
return str_replace(['%3A','%2F'], [':', '/'], rawurlencode($url));
}
© 2022 - 2024 — McMap. All rights reserved.