Convert Hex Code into readable string in PHP

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..


echo "\x74\150\x69\163\x20\151\x73\40\x74\145\x73\164\x69\156\x67\40\x6f\156\x6c\171";

echo test['\x74\171\x70\145'];

echo range("\x61","\x7a");


this is un-readable code, I need some php function that can convert those unreadable code into readable it will become like this after convert..


echo "this is testing only";

echo test['type'];

echo range("a","z");


I know i can just echo that hex to change it to readable string, but I have huge php file and lot’s of php file that same like this, so I need php function that can automatically convert them all into readable code.


Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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(
            return chr($m[1]?hexdec($m[2]):octdec($m[2]));

See it in action here:

Solution 2

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


Decoded output


Solution 3

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:


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

Solution 4

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(
        function ($matches) {
            return stripcslashes($matches[0]);

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply