Last active
March 11, 2024 17:06
List bytes and codepoints in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Heart emoji: ❤️ | |
* UTF-8 bytes: E2 9D A4 EF B8 8F | |
* Code points: U+2764 U+FE0F | |
*/ | |
header('Content-Type: text/plain'); | |
$str = '❤️'; | |
// List bytes | |
$bytes1 = []; | |
for ($i = 0, $len = strlen($str); $i < $len; $i++) { | |
$bytes1[] = sprintf('%02X', ord($str[$i])); | |
} | |
echo implode(' ', $bytes1), "\n"; | |
// List bytes (alternative 2) | |
$bytes2 = []; | |
foreach (str_split($str) as $byte) { | |
$bytes2[] = sprintf('%02X', ord($byte)); | |
} | |
echo implode(' ', $bytes2), "\n"; | |
// List bytes (alternative 3) | |
$bytes3 = []; | |
preg_match_all('/./', $str, $matches); | |
foreach ($matches[0] as $byte) { | |
$bytes3[] = sprintf('%02X', ord($byte)); | |
} | |
echo implode(' ', $bytes3), "\n"; | |
// List code points ("?" to each invalid char) | |
$codePoints1 = []; | |
for ($i = 0, $len = mb_strlen($str); $i < $len; $i++) { | |
$codePoints1[] = sprintf('U+%04X', mb_ord(mb_substr($str, $i, 1))); | |
} | |
echo implode(' ', $codePoints1), "\n"; | |
// List code points (alternative 2, "NUL" to each invalid char) | |
$codePoints2 = []; | |
foreach (mb_str_split($str) as $codePoint) { | |
$codePoints2[] = sprintf('U+%04X', mb_ord($codePoint)); | |
} | |
echo implode(' ', $codePoints2), "\n"; | |
// List code points (alternative 3, ignore completely invalid string) | |
$codePoints3 = []; | |
preg_match_all('/./u', $str, $matches); | |
foreach ($matches[0] as $codePoint) { | |
$codePoints3[] = sprintf('U+%04X', mb_ord($codePoint)); | |
} | |
echo implode(' ', $codePoints3), "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment