views:

904

answers:

4

What is the equivalent of JavaScript's encodeURIcomponent in PHP?

+2  A: 

Try rawurlencode. Or to be more precise:

function encodeURIComponent($str) {
    $revert = array('%21'=>'!', '%2A'=>'*', '%27'=>"'", '%28'=>'(', '%29'=>')');
    return strtr(rawurlencode($str), $revert);
}

This function works exactly how encodeURIComponent is defined:

encodeURIComponent escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )

Gumbo
Thank you!I thought I might be able to do it without a function, but ok.
sombe
@Gal: You will only need that function if you need an identical output.
Gumbo
Nice, you can see the comparison between functions here: http://devpro.it/examples/php_js_escaping.php
philfreo
A: 

Did you try urlencode ?

rochal
yes. the problem is that it's not entirely like encodeURI, it converts every character, even ^I wanted something that would function the exact same way without me having to intervene ^^.
sombe
A: 

http_build_query

Josh Ribakoff
A: 
Catwashere