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?
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.
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.
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 (” “).
if you have a parameter $string and want to replace it's apace to underscore(_). $string = "Hello All."; $newString = str_replace(' ', '_', $string);
Use the rawurlencode
function instead.
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.
I believe that, if you need to use the %20
variant, you could perhaps use rawurlencode()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With