PHP equivalent for javascript escape/unescape

后端 未结 3 858
半阙折子戏
半阙折子戏 2020-12-10 05:45

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

相关标签:
3条回答
  • 2020-12-10 06:01

    PHP:

    rawurlencode("your funky string");
    

    JS:

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

    Don't use escape as it is being deprecated.

    0 讨论(0)
  • 2020-12-10 06:03
    rawurldecode('%73%6F%6D%65%74%68%69%6E%67');
    
    0 讨论(0)
  • 2020-12-10 06:07

    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
    
    0 讨论(0)
提交回复
热议问题