简体   繁体   中英

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. 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:

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

If your text is not UTF-8, but some other encoding, then you can use

$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' .

This works because in PHP, strings are just arrays of bytes. 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. You could try using the function quoted_printable_encode (requires PHP 5.3 or higher).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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