PHP string to hex

10,356

Solution 1

function strtohex($string)
{
  $string = str_split($string);
  foreach($string as &$char)
    $char = "\x".dechex(ord($char));
  return implode('',$string);
}

print strtohex("[0-9A-Za-z\+/=]*");

The above code will give you

\x5b\x30\x2d\x39\x41\x2d\x5a\x61\x2d\x7a\x5c\x2b\x2f\x3d\x5d\x2a

I'm aware that it doesn't look like the output you expect, but that doesn't seem to be string to hex at all.

Solution 2

If you want to perform such a string obfuscation, then use something like @Kristians approach. And you can alternate between the two encoding methods with e.g.:

 $char = (++$i%2) ? "\x".dechex(ord($char)) : "\\".decoct(ord($char));
Share:
10,356
KodeFor.Me
Author by

KodeFor.Me

By using the most recent technologies, striving to produce reliable, modern and easy to use applications for end users. After introducing me to the list of CodePoet WordPress consultants, I have devoted almost entirely in development of themes and plugins, while studying techniques and technologies that improve the user experience, such as speed optimization and responsive design. In now days, I have become a Full Stack Developer both for WordPress, Synfomy and Vue.Js, I am capable of design and build Rest APIs, as well to consume and integrate third party Rest APIs to applications need to be connected with the external world

Updated on June 04, 2022

Comments

  • KodeFor.Me
    KodeFor.Me almost 2 years

    I have a string like that:

    [0-9A-Za-z\+/=]*
    

    How can I converted in the following form:

    "\133\x30\55\x39\101\x2d\132\x61\55\x7a\134\x2b\57\x3d\135\x2a"
    

    Is there any function for that ?

  • KodeFor.Me
    KodeFor.Me over 12 years
    Cool ! Thanks ! :) I will mark your answer as answer after the 5 minutes limitation :)