16

Is there any clean and easy way to urlencode() an arbitrary string but leave slashes (/) alone?

2
  • For what purpose you are doing that? any specific case? Feb 13, 2014 at 13:32
  • @AshwinP My specific case is allowing a user to specify a link URL manually.
    – Cobra_Fast
    Feb 13, 2014 at 14:16

6 Answers 6

22
  1. Split by /
  2. urlencode() each part
  3. Join with /
1
  • 25
    As a one-liner: implode('/', array_map('urlencode', explode('/', $str))); Mar 13, 2015 at 4:38
12

You can do like this:

$url = "http://www.google.com/myprofile/id/1001";
$encoded_url = urlencode($url);
$after_encoded_url = str_replace("%2F", "/", $url);
5

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.

2

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);
1
  • 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
0

Yes, by properly escaping the individual parts before assembling them with slashes:

$url = urlencode($foo) . '/' . urlencode($bar) . '/' . urlencode($baz);
0

$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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.