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

Gal picture Gal · Nov 14, 2009 · Viewed 63.4k times · Source

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

Answer

Gumbo picture Gumbo · Nov 14, 2009

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, - _ . ! ~ * ' ( )