Convert hex code to readable string in PHP

Hi StackOverflow Community,

Here is my question, how to convert php with hex code to readable string? In what I mean, everything is inside this 2 php code ..

<?php 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"); ?> 

it is not readable code, I need some php function that can convert these unreadable codes into readable code ... so it will be converted after that.

 <?php echo "this is testing only"; echo test['type']; echo range("a","z"); ?> 

I know that I can just respond to this hex text to change it to a readable line, but I have a huge php file and a lot of php files that are just like this, so I need a php function that can automatically convert them all into readable code.

Thanks..

+4
source share
3 answers

It seems your code is confused not only with hexadecimal escape sequences, but also with octal. I wrote this function to decode it:

 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 here: http://codepad.viper-7.com/NjiL84

+11
source

I had mixed content, where besides hex and oct there were also regular characters.

So, to update the Sean code above, I added the 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); } 

Line example

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

Decoded output

 "json_decode" 
+6
source

To achieve this, you can use the built-in PHP function urldecode (). 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 be deduced: this is testing only

- seekers01

+3
source

All Articles