matt
matt

Reputation: 44293

PHP: convert spaces in string into %20?

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?

Upvotes: 112

Views: 139688

Answers (3)

David Thomas
David Thomas

Reputation: 253318

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

Upvotes: 29

Matthew Flaschen
Matthew Flaschen

Reputation: 284816

Use the rawurlencode function instead.

Upvotes: 267

Alnitak
Alnitak

Reputation: 339816

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.

Upvotes: 33

Related Questions