質問

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

役に立ちましたか?

解決

  1. Split by /
  2. urlencode() each part
  3. Join with /

他のヒント

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);

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top