Convert Hex Code into readable string in PHP

后端 未结 4 510
[愿得一人]
[愿得一人] 2020-12-11 06:26

Hi StackOverflow Community,

Here is my question, how to convert php that has hex code into readable string ? On what I mean is all inside this 2 php code..



        
相关标签:
4条回答
  • 2020-12-11 06:53

    I had mixed content where besides hex and oct there was also normal chars.

    So to update Sean's code above I added following

    function decode_code($code)
    {
        return preg_replace_callback('@\\\(x)?([0-9a-f]{2,3})@',
            function ($m) {
                if ($m[1]) {
                    $hex = substr($m[2], 0, 2);
                    $unhex = chr(hexdec($hex));
                    if (strlen($m[2]) > 2) {
                        $unhex .= substr($m[2], 2);
                    }
                    return $unhex;
                } else {
                    return chr(octdec($m[2]));
                }
            }, $code);
    }
    

    Example string

    "\152\163\x6f\x6e\137d\x65\143\157\x64e"
    

    Decoded output

    "json_decode"
    
    0 讨论(0)
  • 2020-12-11 06:55

    You could also use stripcslashes if there are no other escape sequences or if you don't mind converting not only hex escape sequences, but also some special characters (such as \0, \a, \b, \f, \n, \r, \t and \v).

    But if you'd like to convert only hex sequences, you might use preg_replace_callback to limit what sequences should be changed, like this:

    function hex2str($string) {
        return preg_replace_callback(
            '/(\\\\x[a-f\d]{2})+/i', 
            function ($matches) {
                return stripcslashes($matches[0]);
            },
            $string
        );
    }
    
    0 讨论(0)
  • 2020-12-11 06:57

    It seems your code is obfuscated not only with hex escape sequences, but with octal as well. I've written this function to decode it for you:

    function decode_code($code){
        return preg_replace_callback(
            "@\\\(x)?([0-9a-f]{2,3})@",
            function($m){
                return chr($m[1]?hexdec($m[2]):octdec($m[2]));
            },
            $code
        );
    }
    

    See it in action here: http://codepad.viper-7.com/NjiL84

    0 讨论(0)
  • 2020-12-11 07:06

    You can use PHP's native urldecode() function to achieve this. Just pass the hex encoded string to the function and the output will be a string in readable format.

    Here is a sample code to demonstrate:

    <?php
    
    echo urldecode("\x74\150\x69\163\x20\151\x73\40\x74\145\x73\164\x69\156\x67\40\x6f\156\x6c\171");
    
    ?>
    

    This should output: this is testing only

    -- seekers01

    0 讨论(0)
提交回复
热议问题