Search code examples
phpstringunicodehex

Encoding/decoding string in hexadecimal and back


Given a string that may contain any character (including a unicode characters), how can I convert this string into hexadecimal representation, and then reverse and obtain from hexadecimal this string?


Solution

  • Use pack() and unpack():

    function hex2str($hex) {
      return pack('H*', $hex);
    }
    
    function str2hex($str) {
      $unpacked = unpack('H*', $str);
      return array_shift($unpacked);
    }
    
    $txt = 'This is test';
    $hex = str2hex($txt);
    $str = hex2str($hex);
    
    echo "{$txt} => {$hex} => {$str}\n";
    

    would produce

    This is test => 546869732069732074657374 => This is test