102

How can I convert spaces in string into %20?

Here is my attempt:

$str = "What happens here?";
echo urlencode($str);

The output is "What+happens+here%3F", so the spaces are not represented as %20.

What am I doing wrong?

Michael Currie
  • 13,721
  • 9
  • 42
  • 58
matt
  • 42,713
  • 103
  • 264
  • 397

3 Answers3

251

Use the rawurlencode function instead.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • 3
    Beware if you use this for url (not its query part), converted slashed will cause the url not to work. So if you just need to take care of spaces (maybe for that URL), I suggest str_replace. – Lukáš Řádek Oct 10 '19 at 11:04
32

The plus sign is the historic encoding for a space character in URL parameters, as documented in the help for the urlencode() function.

That same page contains the answer you need - use rawurlencode() instead to get RFC 3986 compatible encoding.

Community
  • 1
  • 1
Alnitak
  • 334,560
  • 70
  • 407
  • 495
28

I believe that, if you need to use the %20 variant, you could perhaps use rawurlencode().

David Thomas
  • 249,100
  • 51
  • 377
  • 410