Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 756
matt Avatar asked Apr 06 '11 20:04

matt


People also ask

How to remove spaces from string PHP?

The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string. rtrim() - Removes whitespace or other predefined characters from the right side of a string.

How can I replace multiple characters in a string in PHP?

Approach 1: Using the str_replace() and str_split() functions in PHP. The str_replace() function is used to replace multiple characters in a string and it takes in three parameters. The first parameter is the array of characters to replace.

How remove all special characters from a string in PHP?

Using str_replace() Method: The str_replace() method is used to remove all the special characters from the given string str by replacing these characters with the white space (” “).

How do you put underscore between words in PHP?

if you have a parameter $string and want to replace it's apace to underscore(_). $string = "Hello All."; $newString = str_replace(' ', '_', $string);


3 Answers

Use the rawurlencode function instead.

like image 113
Matthew Flaschen Avatar answered Oct 09 '22 04:10

Matthew Flaschen


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.

like image 29
Alnitak Avatar answered Oct 09 '22 04:10

Alnitak


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

like image 27
David Thomas Avatar answered Oct 09 '22 05:10

David Thomas