Created
October 22, 2021 09:27
-
-
Save IonBazan/b0d6165b2dfa1afc6329ea885e1feeb5 to your computer and use it in GitHub Desktop.
Country code to country flag Emoji (PL -> π΅π±)
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 | |
/** | |
* Converts country code (ISO 3166-1) to its emoji flag representation (PL -> π΅π±). | |
* | |
* This solution supports both lowercase and uppercase codes using modulo 32 . | |
* Since it doesn't perform any validation, you should make sure the code is a valid country code first. | |
* | |
* 0x1F1E5 is a code of character right before "REGIONAL INDICATOR SYMBOL LETTER A" (π¦). | |
* | |
* Since there are 32 letters in the ASCII and A is at code 65 (dec), modulo operation returns: | |
* - 1 for "A" and "a" | |
* - 2 for "B" and "b" | |
* etc. | |
*/ | |
function country2flag(string $countryCode): string | |
{ | |
return (string) preg_replace_callback( | |
'/./', | |
static fn (array $letter) => mb_chr(ord($letter[0]) % 32 + 0x1F1E5), | |
$countryCode | |
); | |
} | |
echo country2flag('PL'); // π΅π± | |
echo country2flag('SG'); // πΈπ¬ | |
echo country2flag('us'); // πΊπΈ |
Good work.
Thanks!
I just did the same in Javascript based off this code:
function country2flag(countryCode) {
return countryCode.replace(/./g, (letter) => String.fromCodePoint((letter.charCodeAt(0) % 32) + 0x1F1E5));
}
thanks : )
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sweet!