Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace the "+" plus sign with its corresponding url encoding of "%2B"?

Tags:

string

php

I'm having some trouble replacing the "+" sign with its urlencoded string of "%2B". How can I do this?

This is what I've tried:

Text Entered into text box:

plus(+) 

I then urlencode the string:

$string = urlencode($string); 

String now looks like:

plus%28+%29 

I want to have the "+" urlencoded, or else when I urldecode() the data to display in browser I end up with:

plus( )  

because urldecode() interprets the "+" to be a space.

I tried using php's str_replace() but I keep getting a "NULL" returned as the value for "$new_string":

$new_string = str_replace('+', '%2B', $string); 

Any ideas?

Thanks in advance!

like image 787
Ronedog Avatar asked Jan 21 '11 21:01

Ronedog


People also ask

How do you handle plus sign in URL?

URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits. URLs cannot contain spaces. URL encoding normally replaces a space with a plus (+) sign or with %20.

What is %2f in a URL?

URL encoding converts characters into a format that can be transmitted over the Internet. - w3Schools. So, "/" is actually a seperator, but "%2f" becomes an ordinary character that simply represents "/" character in element of your url.

What symbols should be URL encoded?

Any character that is not an alphabetic character, a number, or a reserved character being used needs to be encoded. URLs use the ASCII (“American Standard Code for Information Interchange”) character-set and so encoding must be to a valid ASCII format.


2 Answers

That is strange. When I use urlencode on plus(+) I get plus%28%2B%29. Make sure you're using it correctly.

You might also try rawurlencode. It will encode spaces as %20 instead of +.

like image 192
John Kugelman Avatar answered Sep 21 '22 22:09

John Kugelman


That helped me:

function _rawurlencode($string) {     $string = rawurlencode(str_replace('+','%2B',$string));     return $string; } 
like image 37
Norman Huth Avatar answered Sep 19 '22 22:09

Norman Huth