21

Is there some encodeURI() function in PHP that does not encode: ~!@#$&*()=:/,;?+'?

2
  • So, which characters do you want it to encode? Commented Feb 8, 2011 at 4:37
  • 1
    you may need to go custom here and decode back out the chars you'd like to keep, if that's a short list Commented Feb 8, 2011 at 5:53

3 Answers 3

31

I'm using this now

function encodeURI($url) { // http://php.net/manual/en/function.rawurlencode.php // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURI $unescaped = array( '%2D'=>'-','%5F'=>'_','%2E'=>'.','%21'=>'!', '%7E'=>'~', '%2A'=>'*', '%27'=>"'", '%28'=>'(', '%29'=>')' ); $reserved = array( '%3B'=>';','%2C'=>',','%2F'=>'/','%3F'=>'?','%3A'=>':', '%40'=>'@','%26'=>'&','%3D'=>'=','%2B'=>'+','%24'=>'$' ); $score = array( '%23'=>'#' ); return strtr(rawurlencode($url), array_merge($reserved,$unescaped,$score)); } 

It basically rawurlencodes everything, and then decodes a few things back (as Zanlok suggested in his comment). This should conform to the Mozilla specs of encodeURI.

And following MDN, 'if one wishes to follow the more recent RFC3986 for URLs', add

function fixedEncodeURI($url) { return strtr(encodeURI($url),array('%5B'=>'[', '%5D'=>']')); } 
Sign up to request clarification or add additional context in comments.

3 Comments

You can add '%5B'=>'[', '%5D'=>']' to reserved chars to be match the RFC3986 (IPV6 brackets)
@mems, thanks for the suggestion. I'm following the MDN specs - I'll wait for those to be updated.
@mems no need of this. it take care self. but there is one issue with [ ' ] single quotes. it doesn't replace Single Quotes. so I added my solution. you can check it....
21

Here's an alternate version based on ECMA-262 spec:

function encodeURI($uri) { return preg_replace_callback("{[^0-9a-z_.!~*'();,/?:@&=+$#-]}i", function ($m) { return sprintf('%%%02X', ord($m[0])); }, $uri); } 

Comments

0

you can try my solution. I fixed an issue that was related to Single Quotes '. After that URL was encoded properly as the browser does.

function encodeBaseURI($uri) { $symbols = array( '%2D'=>'-','%5F'=>'_','%2E'=>'.','%21'=>'!', '%7E'=>'~', '%2A'=>'*', '%27'=>"'", '%28'=>'(', '%29'=>')', '%3B'=>';','%2C'=>',','%2F'=>'/','%3F'=>'?','%3A'=>':', '%40'=>'@','%26'=>'&','%3D'=>'=','%2B'=>'+','%24'=>'$','%23'=>'#' ); return Str::replace("'" , "%22",strtr(rawurlencode($uri), $symbols)); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.