9

What is the PHP equivalent of MySQL's UNHEX()?

For instance, the following query and PHP function should provide the same value.

SELECT UNHEX(c1) AS unhexed_c1 FROM table;

$unhexed_c1=PHPs_UNHEX_Equivalent($c1);
user1032531
  • 24,767
  • 68
  • 217
  • 387

4 Answers4

14

There's a built-in function called hex2bin if you're running PHP >= 5.4.

Joel Hinz
  • 24,719
  • 6
  • 62
  • 75
11

It can be done with pack:

$unhexed = pack('H*', $hexstring);
dev-null-dweller
  • 29,274
  • 3
  • 65
  • 85
  • 1
    Why pack instead of hex2bin (assuming you are running PHP 5.4 or greater)? – user1032531 Dec 25 '14 at 14:54
  • 2
    In the time of writing this answer, most hosting companies that I have used were stuck with php 5.3.x. Even now many popular frameworks / cms / blog platforms targets php 5.3 or even 5.2, so my answer was not assuming that. – dev-null-dweller Dec 26 '14 at 09:23
5

See How to convert hex to string or text in php:

  function unhex($hex) {
    for($i=0;$i<strlen($hex);$i+=2)
       $str .= chr(hexdec(substr($hex,$i,2)));

    return $str;
  }
Community
  • 1
  • 1
dajavax
  • 3,060
  • 1
  • 14
  • 14
2

I think you look for hex2bin