PHP: convert spaces in string into %20?

PhpStringUrlencode

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

Use the rawurlencode function instead.

Solution 2 - Php

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.

Solution 3 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmattView Question on Stackoverflow
Solution 1 - PhpMatthew FlaschenView Answer on Stackoverflow
Solution 2 - PhpAlnitakView Answer on Stackoverflow
Solution 3 - PhpDavid ThomasView Answer on Stackoverflow