如何将文本转换为\ x代码?

时间:2011-09-06 13:16:01

标签: php hex encode

我想将普通文本转换为\ x代码,例如\ x14 \ x65 \ x60

例如:

normal text = "base64_decode"
converted \x codes for above text = "\x62\141\x73\145\x36\64\x5f\144\x65\143\x6f\144\x65"

怎么做?提前谢谢。

6 个答案:

答案 0 :(得分:5)

ord()函数为您提供单个字节的十进制值。 dechex()将其转换为十六进制。所以要做到这一点,循环遍历字符串中的每个字符并应用这两个函数。

答案 1 :(得分:5)

PHP 5.3 one-liner:

echo preg_replace_callback("/./", function($matched) {
    return '\x'.dechex(ord($matched[0]));
}, 'base64_decode');

输出\x62\x61\x73\x65\x36\x34\x5f\x64\x65\x63\x6f\x64\x65

答案 2 :(得分:3)

$str = 'base64_decode';
$length = strlen($str);
$result = '';

for ($i = 0; $i < $length; $i++) $result .= '\\x'.str_pad(dechex(ord($str[$i])),2,'0',STR_PAD_LEFT);

print($result);

答案 3 :(得分:1)

这是工作代码:

function make_hexcodes($text) {
    $retval = '';
    for($i = 0; $i < strlen($text); ++$i) {
        $retval .= '\x'.dechex(ord($text[$i]));
    }

    return $retval;
}

echo make_hexcodes('base64_decode');

<强> See it in action

答案 4 :(得分:0)

对于dechex(ord())的替代方案,您还可以使用bin2hex($char)sprintf('\x%02X')unpack('H*', $char)。另外,您可以将preg_replace_callbackarray_map一起使用,而不是使用str_split

echo implode(array_map(function($char) {
    return '\x' . bin2hex($char);
}, (array) str_split($word)));
echo implode(array_map(function($char) {
    return '\x' . implode(unpack('H*', $char));
}, (array) str_split($word)));
echo implode(array_map(function($char) {
    return sprintf('\x%02X', ord($char));
}, (array) str_split($word)));

示例:https://3v4l.org/6Pc6X

bin2hex

echo implode(array_map(function($char) {
    return '\x' . bin2hex($char);
}, (array) str_split('base64_decode')));

结果

\x62\x61\x73\x65\x36\x34\x5f\x64\x65\x63\x6f\x64\x65

打开包装

echo implode(array_map(function($char) {
    return '\x' . implode(unpack('H*', $char));
}, (array) str_split('base64_decode')));

结果

\x62\x61\x73\x65\x36\x34\x5f\x64\x65\x63\x6f\x64\x65

sprintf

echo implode(array_map(function($char) {
    return sprintf('\x%02X', ord($char));
}, (array) str_split('base64_decode')));

结果

\x62\x61\x73\x65\x36\x34\x5f\x64\x65\x63\x6f\x64\x65

答案 5 :(得分:0)

我未阅读此代码 \ ud83d \ udc33 ?

function unicode_decode(string $str)
    {
       str="Learn Docker in 12 Minutes \ud83d\udc33"
        return preg_replace_callback('/u([0-9a-f]{4})/i', function ($match) {
            return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
        }, $str);
    }