Is there some encodeURI() function in PHP that does not encode: ~!@#$&*()=:/,;?+'?
2
- So, which characters do you want it to encode?Sam Dufel– Sam Dufel2011-02-08 04:37:37 +00:00Commented Feb 8, 2011 at 4:37
- 1you may need to go custom here and decode back out the chars you'd like to keep, if that's a short listzanlok– zanlok2011-02-08 05:53:41 +00:00Commented Feb 8, 2011 at 5:53
Add a comment |
3 Answers
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'=>']')); } 3 Comments
mems
You can add
'%5B'=>'[', '%5D'=>']' to reserved chars to be match the RFC3986 (IPV6 brackets)commonpike
@mems, thanks for the suggestion. I'm following the MDN specs - I'll wait for those to be updated.
pankaj
@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....
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
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)); }