Is there any clean and easy way to urlencode()
an arbitrary string but leave slashes (/
) alone?
-
For what purpose you are doing that? any specific case?– Ashwin ParmarFeb 13, 2014 at 13:32
-
@AshwinP My specific case is allowing a user to specify a link URL manually.– Cobra_FastFeb 13, 2014 at 14:16
6 Answers
- Split by
/
urlencode()
each part- Join with
/
-
25As a one-liner:
implode('/', array_map('urlencode', explode('/', $str)));
Mar 13, 2015 at 4:38
You can do like this:
$url = "http://www.google.com/myprofile/id/1001";
$encoded_url = urlencode($url);
$after_encoded_url = str_replace("%2F", "/", $url);
Basically what @clovecooks said, but split() is deprecated as of 5.3:
$path = '/path with some/illegal/characters.html';
$parsedPath = implode('/', array_map(function ($v) {
return rawurlencode($v);
}, explode('/', $path)));
// $parsedPath == '/path%20with%20some/illegal/characters.html';
Also might want to decode before encoding, in case the string is already encoded.
I suppose you are trying to encode a whole HTTP url.
I think the best solution to encode a whole HTTP url is to follow the browser strickly.
If you just skip slashes, then you will get double-encode issue if the url has already been encoded.
And if there are some parameters in the url, (?
, &
, =
, #
are in the url) the encoding will break the link.
The browsers only encode ,
"
, <
, >
, `
and multi-byte characters. (Copy all symbols to the browser, you will get the list)
You only need to encode these characters.
echo preg_replace_callback("/[\ \"<>`\\x{0080}-\\x{FFFF}]+/u", function ($match) {
return rawurlencode($match[0]);
}, $path);
-
you are missing some characters, i suggest this :
/[\ \"<>`\\x{0080}-\\x{FFFF}\\x{0000}-\\x{001F}\\x{007F}]+/u
Oct 13, 2020 at 12:43
Yes, by properly escaping the individual parts before assembling them with slashes:
$url = urlencode($foo) . '/' . urlencode($bar) . '/' . urlencode($baz);
$encoded = implode("/", array_map(function($v) { return urlencode($v); }, split("/", $url)));
This will split the string, encode the parts and join the string together again.