BCP47Tag is a robust PHP library for working with BCP 47 language tags:
- βοΈ Validates against the real IANA Language Subtag Registry
- βοΈ ABNF-compliant (RFCβ―5646)
- βοΈ Supports language, script, region, variant, grandfathered tags
- βοΈ Auto-normalizes casing & separators (
en_usβen-US) - βοΈ Automatically expands collapsed ranges from the registry
- βοΈ Resolves partial language tags (e.g.,
enβen-US) using custom canonical matching, with scoring - βοΈ Error handling via clear exception types
- βοΈ Lightweight
LanguageTagVO for validated tags - βοΈ Works perfectly with
ext-intlβno surprises upon feeding ICU - βοΈ Easy fallback mechanism
- οΈπ«§ Supports grandfathered tags so old, they still remember when Unicode 2.0 was hot
- π Accepts
i-klingonandi-enochianfor your occult projects - π€
ABNFso clean, linguists shed a single tear
Good question β and the answer is: you should keep using it!
ext-intl (ICU) is brilliant at formatting if your tag is clean.
However, it does not:
- β Validate that your tag fully follows the BCP 47 ABNF rules.
- β Reject or warn about grandfathered or deprecated subtags.
- β Match your tags against the authoritative IANA Language Subtag Registry.
- β
Resolve partial input (
enβen-US) to a known canonical list. - β
Enforce known tags only with
knownTags+requireCanonical.
If youβre in Symfony, you might also use
#[Assert\Locale]for basic input validation.
And thatβs fine for checking user input β but it stops at structure. It wonβt canonicalize, resolve, or check IANA.
π So the best practice:
- β Use BCP47Tag to validate & normalize.
- β
Hand the cleaned tag to
ext-intlor whatever else you have for formatting & display. - β Trust youβll never feed ICU any garbage.
- β Carry around immutable LanguageTag value object across your code base instead of string
BCP47Tag: RFC 5646 + IANA + real normalization + fallback + resolution.
No hustle with regex, str_replace() or guesswork.
composer require lhcze/bcp47-taguse LHcze\BCP47\BCP47Tag;
// Just normalize & validate
$tag = new BCP47Tag('en_us');
echo $tag->getNormalized(); // "en-US"
echo $tag->getICUformat(); // "en_US"
// With canonical matching
$tag = new BCP47Tag('en', useCanonicalMatchTags: ['de-DE', 'en-US']);
echo $tag->getNormalized(); // "en-US"
// Use fallback if invalid
$tag = new BCP47Tag('notreal', 'fr-FR');
echo $tag->getNormalized(); // fr-FR
// Invalid input β exception
try {
new BCP47Tag('invalid!!');
} catch (BCP47InvalidLocaleException $e) {
echo $e->getMessage();
}
// Feed to ext-intl
$icu = $tag->getICULocale(); // en_US
echo Locale::getDisplayLanguage($icu); // English
// LanguageTag VO
$langTag = $tag->getLanguageTag();
echo $langTag->getLanguage(); // "en"
echo $langTag->getRegion(); // "US"
echo (string) $langTag; // "en-US"-
Normalize + parse
Clean casing/formatting and parse into components. -
Validate against IANA
Broken input or fallback triggers explicit exceptions:BCP47InvalidLocaleExceptionBCP47InvalidFallbackLocaleException
-
Canonical matching (optional)
- Pass an array of
useCanonicalMatchTags - Each is matched and scored:
+100 language match, +10 region, +1 script - Highest score wins.
- Same score makes the first one to have it to make a home run
- Pass an array of
-
LanguageTag VO
Immutable, validated,Stringable&JsonSerializable.
BCP47Tag uses a precompiled static PHP snapshot of the latest IANA Language Subtag Registry to validate languages, scripts, regions, variants, and grandfathered tags. The registry is loaded once per process, kept hot in OPcache for maximum speed.
- β ISO language, script, region, variants
- β
Grandfathered/deprecated tags (e.g.,
i-klingon) - β Collapsed registry ranges are auto-expanded
β οΈ Extensions & private-use subtags (future)
| Method | Description |
|---|---|
__construct(string $input, ?string $fallback, ?array $useCanonicalMatchTags) |
Main entry |
getInputLocale() |
Original input string |
getNormalized() |
RFCβ5646 formatted tag |
getICUformat() |
Underscore variant (xx_XX) |
getLanguageTag() |
Returns LanguageTag VO |
__toString() / jsonSerialize() |
Returns normalized string |
The syntax tags must follow is defined by RFC 5646 in ABNF:
langtag = language
["-" script]
["-" region]
*("-" variant)
*("-" extension)
["-" privateuse]Examples:
- β
enβ valid - β
en-USβ valid - β
zh-Hant-CNβ valid - β
i-klingonβ valid (grandfathered) - β
en-US-x-privateβ valid (extension/private use) - β
en-US--USβ invalid
BCP47Tag respects this ABNF, so your tags match the real spec β no hidden assumptions.
Use cases include:
- Validating API
Accept-Languageheaders - Multi-regional CMS deployments
- Internationalization pipelines
- Locale-dependent services where mis-typed tags lead to silent failures
- PHP 8.3+
ext-intl
composer qa- β IANA Language Subtag Registry integration
- β Language, script, region, variant validation
- β Lazy singleton registry loader
- β Static PHP snapshot of the IANA registry for ultra-fast lookups
- β Canonical matching with scoring
- β Typed exceptions for flow control
- βοΈ Extension/subtag support (planned)
- βοΈ Additional data use from IANA registry (suppress-script subtag, preferred, prefix)
- βοΈ Auto-registry refresh script
𧬠Now go and boldly canonicalize strange new tags the BCP 47 way! πβ¨