字符串解码
十六进制字符串编解码的 PHP 实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
/** * 将字符串转化为16进制编码形式 * * @param string $input * @param bool $upper 是否返回大写形式 * @return string */ public static function string2hex($input, $upper = true) { $result = preg_replace('/[0-9a-z]{2}/i', '%$0', bin2hex($input)); return !!$upper ? strtoupper($result) : $result; } /** * 将16进制编码转换为字符串 * * @param string $input * @return string */ public static function hex2string($input) { $handler = function ($matches) { $hex = $matches[1]; //return pack('H*', $hex); return hex2bin($hex); }; return preg_replace_callback('/\%([0-9a-z]{2})/i', $handler, $input); } |