PHP equivalent for javascript escape/unescape


Let's say I have a string: something

When I escape it in JS I get this: %73%6F%6D%65%74%68%69%6E%67

so I can use this code in JS to decode it:

 document.write(unescape('%73%6F%6D%65%74%68%69%6E%67'));

I need the escape function in PHP which will do the same (will encode something to : %73%6F%6D%65%74%68%69%6E%67)

How to do that ?

PHP:

rawurlencode("your funky string");

JS:

decodeURIComponent('your%20funky%20string');

Don't use escape as it is being deprecated.


rawurldecode('%73%6F%6D%65%74%68%69%6E%67');

Some clarification first:

Let's say I have a string: something
When I escape it in JS I get this: %73%6F%6D%65%74%68%69%6E%67

That's wrong. (Btw, the JS escape() function is deprecated. You should use encodeURIComponent() instead!)

so I can use this code in JS to decode it: document.write(unescape('%73%6F%6D%65%74%68%69%6E%67'));

Yep, this will write "something" to the document (as escape(), also unescape() is deprecated; use decodeURIComponent() instead).


To your question:

I need the [snip] function in PHP which [snip] encode something to %73%6F%6D%65%74%68%69%6E%67

What you're looking for is the hexadecimal representation of charachters. So, to get the string "%73%6F%6D%65%74%68%69%6E%67" from the string "something", you would need:

<?php
function stringToHex($string) {
    $hexString = '';
    for ($i=0; $i < strlen($string); $i++) {
        $hexString .= '%' . bin2hex($string[$i]);
    }
    return $hexString;
}

$hexString = stringToHex('something');
echo strtoupper($hexString); // %73%6F%6D%65%74%68%69%6E%67

Backwards:

function hexToString($hexString) {
    return pack("H*" , str_replace('%', '', $hexString));
}

$string = hexToString('%73%6F%6D%65%74%68%69%6E%67');
echo $string; // something