13

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 ?

6
  • 3
    Escaping/encoding !== "encryption". What's the purpose? Commented Mar 20, 2013 at 21:05
  • 1
    urlencode doesn't work? php.net/manual/en/function.urlencode.php Commented Mar 20, 2013 at 21:05
  • 1
    escape('something') != '%73%6F%6D%65%74%68%69%6E%67' Commented Mar 20, 2013 at 21:10
  • what you have there are the ascii hex values. in php you can use chr()/ord() Commented Mar 20, 2013 at 21:13
  • 1
    rawurlencode is the escape equivalent Commented Mar 20, 2013 at 21:24

3 Answers 3

17

PHP:

rawurlencode("your funky string");

JS:

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

Don't use escape as it is being deprecated.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

You might want to elaborate on what this does, why it is useful, etc. SO is about learning, not just answering questions.
3

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

2 Comments

dechex(ord()) == bin2hex
Also update hexToString() function; much easier to use pack() on the string instead of iterating over hex values and use chr(hexdec()) on each.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.