115

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?

3 Answers 3

270

Use the rawurlencode function instead.

Sign up to request clarification or add additional context in comments.

1 Comment

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

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.

Comments

29

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.