简体   繁体   English

PHP,将字符串转换为UTF-8,然后十六进制

[英]PHP, convert string into UTF-8 and then hexadecimal

In PHP, I want to convert a string which contains non-ASCII characters into a sequence of hexadecimal numbers which represents the UTF-8 encoding of these characters. 在PHP中,我想将包含非ASCII字符的字符串转换为代表这些字符的UTF-8编码的十六进制序列。 For instance, given this: 例如,鉴于此:

$text = 'ąćę';

I need to produce this: 我需要产生这个:

C4=84=C4=87=C4=99

How do I do that? 我怎么做?

As your question is written, and assuming that your text is properly UTF-8 encoded to start with, this should work: 在编写问题时,并假设您的文本以正确的UTF-8编码开头,这应该可以:

$text = 'ąćę';
$result = implode('=', str_split(strtoupper(bin2hex($text)), 2));

If your text is not UTF-8, but some other encoding, then you can use 如果您的文字不是UTF-8,而是其他一些编码,则可以使用

$utf8 = mb_convert_encoding($text, 'UTF-8', $yourEncoding);

to get it into UTF-8, where $yourEncoding is some other character encoding like 'ISO-8859-1' . 使其进入UTF-8,其中$yourEncoding是其他一些字符编码,例如'ISO-8859-1'

This works because in PHP, strings are just arrays of bytes. 之所以可行,是因为在PHP中,字符串只是字节数组。 So as long as your text is encoded properly to start with, you don't have to do anything special to treat it as bytes. 因此,只要您对文本进行正确的编码即可开始,那么您无需执行任何特殊操作即可将其视为字节。 In fact, this code will work for any character encoding you want without modification. 实际上,此代码无需修改即可用于您想要的任何字符编码。

Now, if you want to do quoted-printable, then that's another story. 现在,如果您想做quoted-printable,那又是另一回事了。 You could try using the function quoted_printable_encode (requires PHP 5.3 or higher). 您可以尝试使用函数quoted_printable_encode (需要PHP 5.3或更高版本)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM