Skip to content

Instantly share code, notes, and snippets.

@jyxjjj
Last active March 19, 2024 02:07
Show Gist options
  • Save jyxjjj/358ee9d34aafee0895bd674b4f16300a to your computer and use it in GitHub Desktop.
Save jyxjjj/358ee9d34aafee0895bd674b4f16300a to your computer and use it in GitHub Desktop.
ISO-3166-1-Alpha-2 Country Code to Unicode Emoji
<?php
function countryCodeGetEmoji($countryCode = 'XX', $continent = 'XX'): string
{
try {
if (strlen($countryCode) !== 2) {
throw new InvalidArgumentException('Invalid country code');
}
if ($countryCode === 'XX') {
return mb_convert_encoding("&#x1F310;", 'UTF-8', 'HTML-ENTITIES');
}
if ($countryCode === 'T1') {
return mb_convert_encoding("&#x1F310;", 'UTF-8', 'HTML-ENTITIES');
}
$firstLetter = dechex(ord(substr($countryCode, 0, 1)) - 0x41 + 0x1F1E6);
$secondLetter = dechex(ord(substr($countryCode, 1, 1)) - 0x41 + 0x1F1E6);
$flag = mb_convert_encoding("&#x$firstLetter;", 'UTF-8', 'HTML-ENTITIES') . mb_convert_encoding("&#x$secondLetter;", 'UTF-8', 'HTML-ENTITIES');
} catch (Throwable) {
/** @noinspection PhpDuplicateMatchArmBodyInspection */
$flag = match ($continent) {
'AF', 'EU' => mb_convert_encoding("&#x1F30D;", 'UTF-8', 'HTML-ENTITIES'),
'NA', 'SA' => mb_convert_encoding("&#x1F30E;", 'UTF-8', 'HTML-ENTITIES'),
'AS', 'OC' => mb_convert_encoding("&#x1F30F;", 'UTF-8', 'HTML-ENTITIES'),
'AN', 'T1' => mb_convert_encoding("&#x1F310;", 'UTF-8', 'HTML-ENTITIES'),
default => mb_convert_encoding("&#x1F310;", 'UTF-8', 'HTML-ENTITIES'),
};
}
return $flag;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment