Cosmo (PHP) — API reference

Cosmo extends Locale
in package

Table of Contents

Constants

DURATION_UNITS  : array<string|int, mixed> = ['years', 'months', 'weeks', 'days', 'hours', '...
FULL  : int = \IntlDateFormatter::FULL
INTERVAL_DATE_FIELDS  : array<string|int, mixed> = ['y' => \IntlCalendar::FIELD_YEAR, 'M' => \Intl...
INTERVAL_DATE_SKELETONS  : array<string|int, mixed> = ['short' => 'yMd', 'medium' => 'yMMMd']
INTERVAL_TIME_FIELDS  : array<string|int, mixed> = ['a' => \IntlCalendar::FIELD_AM_PM, 'H' => \Int...
KNOWN_COLLATION_OPTIONS  : array<string|int, mixed> = ['numeric' => true, 'caseFirst' => true]
KNOWN_NUMBER_OPTIONS  : array<string|int, mixed> = ['minimumIntegerDigits' => true, 'minimumFracti...
LIST_TYPES  : array<string|int, mixed> = ['conjunction' => 'standard', 'disjunction' =>...
LIST_WIDTHS  : array<string|int, mixed> = ['none' => '', 'short' => '-narrow', 'medium' =...
LONG  : int = \IntlDateFormatter::LONG
MEDIUM  : int = \IntlDateFormatter::MEDIUM
NAME_WIDTHS  : array<string|int, mixed> = ['none' => 4, 'short' => 5, 'medium' => 3, 'lon...
NONE  : int = \IntlDateFormatter::NONE
ROUNDING_MODES  : array<string|int, mixed> = ['ceil' => \NumberFormatter::ROUND_CEILING, 'fl...
SHORT  : int = \IntlDateFormatter::SHORT
SYMBOL_NAMES  : array<string|int, mixed> = ['decimal' => \NumberFormatter::DECIMAL_SEPARAT...
TIME_WIDTHS  : array<string|int, mixed> = ['none' => self::NONE, 'short' => self::SHORT,...
TZ_NAME_PATTERNS  : array<string|int, mixed> = ['long' => 'zzzz', 'short' => 'z', 'shortOffset...
UNIT_WIDTHS  : array<string|int, mixed> = ['short' => 'unitsNarrow', 'medium' => 'unitsSh...

Properties

$locale  : string|null
$modifiers  : array<string|int, mixed>
$subtags  : array<string|int, mixed>

Methods

__construct()  : mixed
addLikelySubtags()  : static
Returns a new Cosmo with likely subtags added (e.g. "en" → "en_Latn_US").
calendar()  : string
Translate the calendar identifier (e.g. "buddhist" -> "Buddhist Calendar")
compact()  : string
Compact notation (e.g. 1200 -> "1.2K", 1200000 -> "1.2M").
compare()  : int
Locale-aware comparison of two strings, suitable for usort().
confusable()  : bool
Whether two strings are visually confusable ('paypal' vs a Cyrillic 'раураl') per UTS #39. Locale-independent.
contains()  : bool
Locale-aware substring test that honours the locale's collation, so accents/case can be ignored. Compares grapheme windows with a Collator (PHP's intl exposes no ICU StringSearch).
country()  : string
Translate the country of a locale (e.g. AU -> Australia)
create()  : Cosmo
createFromHttp()  : Cosmo
createFromSubtags()  : Cosmo
currency()  : string
Returns the localised name or symbol of a currency.
date()  : string
Formats a date value (no time component).
dateRange()  : string
Formats a date or time range using CLDR interval format patterns (e.g. "Feb 2 – 5, 2020").
direction()  : string
Returns the text direction of a language: 'rtl' or 'ltr'.
displayName()  : string
Generic localised display name — a single entry point over the dedicated lookups.
duration()  : string
Formats an undirected duration.
ellipsize()  : string
Truncates text to at most $max graphemes, breaking on a word boundary and appending $ellipsis. Grapheme-aware, so it never splits a combining sequence. Returns the original text if it already fits.
flag()  : string
Returns the emoji of a locale (e.g. AU -> 🇦🇺)
formatMoment()  : string
Formats a date/time value using a custom ICU pattern.
fromAcceptLanguage()  : Cosmo
Creates a Cosmo instance from an HTTP Accept-Language header.
fromSubtags()  : Cosmo
Creates a Cosmo instance from an array of locale subtags instead of a locale string.
get()  : ResourceBundle|int|array<string|int, mixed>|string|null
Retrieves a value from an ICU resource bundle, falling back to the primary language then root.
join()  : string
Joins a list using the locale's conventions (e.g. "A, B, and C"). Built from CLDR listPattern data — PHP reaches ICU directly, so no Intl.ListFormat is needed.
language()  : string
Returns the localised name of a language (e.g. 'en' -> 'English', 'glk' -> 'Gilaki').
lower()  : string
Locale-aware lower-casing.
message()  : string
Formats an ICU message string with the given arguments.
moment()  : string
Formats a date, time, or date+time value using the locale's conventions.
money()  : string
Formats a monetary value using the locale's currency format.
moneyRange()  : string
Formats a monetary range (e.g. "$3.00–$5.00"). Returns '' when no currency is available. Like numberRange(), an approximation of ICU's NumberRangeFormatter.
monthNames()  : array<string|int, string>
Localised month names (January … December), following the active calendar.
number()  : string
Formats a number using the locale's default number format.
numberRange()  : string
Formats a numeric range (e.g. "3–5"). Built from the CLDR `range` pattern ("{0}–{1}") since ext-intl binds no NumberRangeFormatter; unlike ICU's formatter it does not collapse shared parts (always "3–5", never "3–5K").
ordinal()  : string
Formats a number as a localised ordinal (e.g. 1 -> '1st' in English).
parseDate()  : DateTimeImmutable
Parses a localised date written at the given width. The inverse of date().
parseMoment()  : DateTimeImmutable
Parses a moment with a raw ICU pattern. The inverse of formatMoment().
parseMoney()  : array{amount: float, currency: string}
Parses a localised monetary string ('$12.30' -> amount 12.3, currency USD).
parseNumber()  : float
Parses a localised number ('1.234,56' in de -> 1234.56). The inverse of number().
percentage()  : string
Formats a decimal value as a localised percentage (e.g. 0.2 -> '20%').
pluralCategory()  : string
The LDML plural category a number falls into for this locale (e.g. 1 -> 'one', 2 -> 'other' in English). Derived from ICU's plural rules via MessageFormatter (PHP's intl exposes no PluralRules class).
precision()  : string
Formats a number with a fixed number of fraction digits — always exactly $fractionDigits, padding with trailing zeros and rounding as needed. Use it when you want 1 to render as '1.00' and 1.002 to stay '1.00', never '1.0'.
quote()  : string
Wraps a string in the locale's quotation marks (e.g. "text" in English, «text» in Persian).
relativeDuration()  : string
Renders a directed (signed) duration in words: (-3, 'day') -> "3 days ago", (2, 'hour') -> "in 2 hours". The directed counterpart of duration().
relativeDurationBetween()  : string
Renders the directed duration between two moments as relative text, picking the largest sensible unit (e.g. "in 5 days", "3 days ago"). Computes target − reference.
removeLikelySubtags()  : static
Returns a new Cosmo with likely subtags removed (e.g. "en_Latn_US" → "en").
romanize()  : string
Romanises text ('Москва' -> 'Moskva'); shorthand for the 'Any-Latin' transform.
scientific()  : string
Scientific notation (e.g. 12345 -> "1.2345E4").
script()  : string
Returns the localised name of a script (e.g. 'Hans' -> 'Simplified Chinese').
sort()  : array<string|int, mixed>
Returns a new array sorted by the locale's collation rules.
spellout()  : string
Spells out a number in the locale's language (e.g. 42 -> 'forty-two' in English).
splitGraphemes()  : array<string|int, string>
Splits text into grapheme clusters (user-perceived characters), so combining marks and emoji ZWJ sequences stay intact.
splitSentences()  : array<string|int, string>
Splits text into sentences using the locale's sentence-boundary rules.
splitWords()  : array<string|int, string>
Splits text into words using the locale's word-boundary rules, keeping only word-like segments (drops whitespace and punctuation).
supportedValues()  : array<string|int, string>
The values the runtime's ICU supports for a given key. PHP's intl surface enumerates 'timeZone' (IntlTimeZone), 'currency' (CLDR currency bundle) and 'transliterator' (Transliterator::listIDs); other keys ('calendar', 'collation', 'numberingSystem', 'unit') are not reachable through it and raise rather than return a hardcoded list.
suspicious()  : bool
Whether a string fails ICU's default spoof checks (mixed scripts, restriction level, invisible characters) per UTS #39.
symbol()  : string
Returns a localised number symbol (e.g. 'decimal', 'group', 'percent').
time()  : string
Formats a time value (no date component).
timeZoneName()  : string
Localised display name of a time zone (e.g. "Australian Eastern Standard Time").
transliterate()  : string
Runs an ICU transform over the text — script conversion, romanisation, accent folding ('Any-Latin; Latin-ASCII' makes ASCII slugs).
unit()  : string
Formats a measurement value with a localised unit (e.g. 2.19 gigabytes, 26 degrees Celsius).
upper()  : string
Locale-aware upper-casing (e.g. Turkish dotted/dotless I). Falls back to the language-neutral ICU casing when the locale has no special rules.
weekdayNames()  : array<string|int, string>
Localised weekday names, Sunday first (matching ICU symbol order).
weekInfo()  : array{firstDay: int, weekend: int[], minimalDays: int}
Week conventions for the locale: first day of the week, weekend days, and the minimal days in the first week. Days are 1 = Monday … 7 = Sunday (ISO 8601), matching the cosmo-js port.
applyCollationOptions()  : void
Applies portable collation tailoring ('numeric', 'caseFirst') to a Collator.
applyListPattern()  : string
applyNumberOptions()  : void
Applies a portable NumberOptions array to a NumberFormatter.
bundleToPluralMessage()  : string
durationParts()  : string
Renders a multi-unit duration by formatting each unit with unit() and joining them with the locale's CLDR unit-list pattern (PHP's intl has no MeasureFormat).
extract()  : ResourceBundle|int|array<string|int, mixed>|string|null
getWidth()  : int
isRtlScript()  : bool
Whether an ISO 15924 script is written right-to-left, derived live from ICU's Unicode property data: the bidi class of the script's first strong character.
listPattern()  : string
Resolves one CLDR list-pattern piece ('2', 'start', 'middle', 'end'), falling back from the width-specific variant to the base type to 'standard'. Each lookup goes through get() so a partial locale override (e.g. en_AU defines only 'end' for 'standard') still inherits the remaining pieces from the parent locale.
maximiseSubtags()  : array<string|int, mixed>|null
Maximised ['language', 'script', 'region'] for a locale per the CLDR likely-subtags algorithm (UTS #35), resolved against ICU's likelySubtags table, or null when nothing matches. Subtags present in the source always win; only missing ones are filled from the table (so az → az_Latn_AZ but az_IQ → az_Arab_IQ, and an explicit script like ar_Latn is never replaced).
nameWidth()  : int
rangePattern()  : string
The locale's CLDR number range pattern ("{0}–{1}"), falling back to root's.
replaceCoreSubtags()  : string
Rebuilds a locale ID with new core language/script/region subtags while preserving its variants and any @keyword extensions, which parseLocale/ composeLocale would otherwise drop.
splitIntervalPattern()  : array<string|int, mixed>
Split a CLDR interval format pattern into its start and end sub-patterns.
toTimestampMs()  : float
Convert a mixed date/time value to a Unix timestamp in milliseconds (for IntlCalendar::setTime()).

Constants

DURATION_UNITS

public array<string|int, mixed> DURATION_UNITS = ['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds', 'milliseconds']

FULL

public int FULL = \IntlDateFormatter::FULL

INTERVAL_DATE_FIELDS

public array<string|int, mixed> INTERVAL_DATE_FIELDS = ['y' => \IntlCalendar::FIELD_YEAR, 'M' => \IntlCalendar::FIELD_MONTH, 'd' => \IntlCalendar::FIELD_DAY_OF_MONTH]

INTERVAL_DATE_SKELETONS

public array<string|int, mixed> INTERVAL_DATE_SKELETONS = ['short' => 'yMd', 'medium' => 'yMMMd']

INTERVAL_TIME_FIELDS

public array<string|int, mixed> INTERVAL_TIME_FIELDS = ['a' => \IntlCalendar::FIELD_AM_PM, 'H' => \IntlCalendar::FIELD_HOUR_OF_DAY, 'h' => \IntlCalendar::FIELD_HOUR, 'm' => \IntlCalendar::FIELD_MINUTE]

KNOWN_COLLATION_OPTIONS

public array<string|int, mixed> KNOWN_COLLATION_OPTIONS = ['numeric' => true, 'caseFirst' => true]

KNOWN_NUMBER_OPTIONS

public array<string|int, mixed> KNOWN_NUMBER_OPTIONS = ['minimumIntegerDigits' => true, 'minimumFractionDigits' => true, 'maximumFractionDigits' => true, 'minimumSignificantDigits' => true, 'maximumSignificantDigits' => true, 'roundingMode' => true, 'roundingIncrement' => true, 'useGrouping' => true, 'signDisplay' => true, 'trailingZeroDisplay' => true, 'roundingPriority' => true, 'notation' => true, 'compactDisplay' => true]

LIST_TYPES

public array<string|int, mixed> LIST_TYPES = ['conjunction' => 'standard', 'disjunction' => 'or', 'unit' => 'unit']

LIST_WIDTHS

public array<string|int, mixed> LIST_WIDTHS = ['none' => '', 'short' => '-narrow', 'medium' => '-short', 'long' => '', 'full' => '']

LONG

public int LONG = \IntlDateFormatter::LONG

MEDIUM

public int MEDIUM = \IntlDateFormatter::MEDIUM

NAME_WIDTHS

public array<string|int, mixed> NAME_WIDTHS = ['none' => 4, 'short' => 5, 'medium' => 3, 'long' => 4, 'full' => 4]

NONE

public int NONE = \IntlDateFormatter::NONE

ROUNDING_MODES

public array<string|int, mixed> ROUNDING_MODES = ['ceil' => \NumberFormatter::ROUND_CEILING, 'floor' => \NumberFormatter::ROUND_FLOOR, 'expand' => \NumberFormatter::ROUND_UP, 'trunc' => \NumberFormatter::ROUND_DOWN, 'halfExpand' => \NumberFormatter::ROUND_HALFUP, 'halfTrunc' => \NumberFormatter::ROUND_HALFDOWN, 'halfEven' => \NumberFormatter::ROUND_HALFEVEN]

SHORT

public int SHORT = \IntlDateFormatter::SHORT

SYMBOL_NAMES

public array<string|int, mixed> SYMBOL_NAMES = ['decimal' => \NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, 'group' => \NumberFormatter::GROUPING_SEPARATOR_SYMBOL, 'grouping' => \NumberFormatter::GROUPING_SEPARATOR_SYMBOL, 'pattern' => \NumberFormatter::PATTERN_SEPARATOR_SYMBOL, 'percent' => \NumberFormatter::PERCENT_SYMBOL, 'permill' => \NumberFormatter::PERMILL_SYMBOL, 'permille' => \NumberFormatter::PERMILL_SYMBOL, 'minus' => \NumberFormatter::MINUS_SIGN_SYMBOL, 'plus' => \NumberFormatter::PLUS_SIGN_SYMBOL, 'exponential' => \NumberFormatter::EXPONENTIAL_SYMBOL, 'exponent' => \NumberFormatter::EXPONENTIAL_SYMBOL, 'currency' => \NumberFormatter::CURRENCY_SYMBOL, 'intlcurrency' => \NumberFormatter::INTL_CURRENCY_SYMBOL, 'monetary' => \NumberFormatter::MONETARY_SEPARATOR_SYMBOL, 'nan' => \NumberFormatter::NAN_SYMBOL, 'infinity' => \NumberFormatter::INFINITY_SYMBOL, 'significant' => \NumberFormatter::SIGNIFICANT_DIGIT_SYMBOL, 'significantdigit' => \NumberFormatter::SIGNIFICANT_DIGIT_SYMBOL, 'digit' => \NumberFormatter::DIGIT_SYMBOL, 'zero' => \NumberFormatter::ZERO_DIGIT_SYMBOL, 'zerodigit' => \NumberFormatter::ZERO_DIGIT_SYMBOL, 'pad' => \NumberFormatter::PAD_ESCAPE_SYMBOL, 'padescape' => \NumberFormatter::PAD_ESCAPE_SYMBOL]

TIME_WIDTHS

public array<string|int, mixed> TIME_WIDTHS = ['none' => self::NONE, 'short' => self::SHORT, 'medium' => self::MEDIUM, 'long' => self::LONG, 'full' => self::FULL]

TZ_NAME_PATTERNS

public array<string|int, mixed> TZ_NAME_PATTERNS = ['long' => 'zzzz', 'short' => 'z', 'shortOffset' => 'O', 'longOffset' => 'OOOO', 'shortGeneric' => 'v', 'longGeneric' => 'vvvv']

UNIT_WIDTHS

public array<string|int, mixed> UNIT_WIDTHS = ['short' => 'unitsNarrow', 'medium' => 'unitsShort', 'long' => 'units', 'full' => 'units']

Properties

$locale read-only

public string|null $locale

$modifiers read-only

public array<string|int, mixed> $modifiers

$subtags read-only

public array<string|int, mixed> $subtags

Methods

__construct()

public __construct([string|null $locale = null ][, array<string|int, mixed> $modifiers = [] ]) : mixed
Parameters
$locale : string|null = null

BCP 47 locale identifier, e.g. en_AU. Defaults to the system locale.

$modifiers : array<string|int, mixed> = []

Optional overrides: 'calendar', 'currency', 'timeZone'.

addLikelySubtags()

Returns a new Cosmo with likely subtags added (e.g. "en" → "en_Latn_US").

public addLikelySubtags() : static

ext-intl wraps neither uloc_addLikelySubtags nor Intl.Locale#maximize, so this implements the CLDR likely-subtags algorithm over ICU's own likelySubtags table.

Return values
static

calendar()

Translate the calendar identifier (e.g. "buddhist" -> "Buddhist Calendar")

public calendar(string $calendar) : string
Parameters
$calendar : string
Return values
string

compact()

Compact notation (e.g. 1200 -> "1.2K", 1200000 -> "1.2M").

public compact(float $value[, string $width = 'short' ]) : string
Parameters
$value : float
$width : string = 'short'

'long'/'full' for long form (e.g. "1.2 million"); anything else (including the default 'short') for the short form (e.g. "1.2M").

Return values
string

compare()

Locale-aware comparison of two strings, suitable for usort().

public compare(string $a, string $b[, array<string|int, mixed> $options = [] ]) : int
Parameters
$a : string
$b : string
$options : array<string|int, mixed> = []
Return values
int

Negative, 0, or positive.

confusable()

Whether two strings are visually confusable ('paypal' vs a Cyrillic 'раураl') per UTS #39. Locale-independent.

public confusable(string $a, string $b) : bool
Parameters
$a : string
$b : string
Return values
bool

contains()

Locale-aware substring test that honours the locale's collation, so accents/case can be ignored. Compares grapheme windows with a Collator (PHP's intl exposes no ICU StringSearch).

public contains(string $haystack, string $needle[, string $sensitivity = 'base' ][, array<string|int, mixed> $options = [] ]) : bool
Parameters
$haystack : string
$needle : string
$sensitivity : string = 'base'

'base' (ignore case & accents, default), 'accent', 'case', or 'variant' (exact).

$options : array<string|int, mixed> = []
Tags
throws
Exception

If $sensitivity is not recognised.

Return values
bool

country()

Translate the country of a locale (e.g. AU -> Australia)

public country([string|Sentinel|null $country = Sentinel::Unset ]) : string
Parameters
$country : string|Sentinel|null = Sentinel::Unset

ISO 3166 country codes or a valid locale

Return values
string

create()

public static create([string $locale = null ][, array<string|int, mixed> $modifiers = [] ]) : Cosmo

Use new Cosmo() directly — PHP 8.4 supports new Cosmo($locale)->method() without parentheses.

Parameters
$locale : string = null
$modifiers : array<string|int, mixed> = []
Return values
Cosmo

createFromHttp()

public static createFromHttp([string|null $header = null ][, array<string|int, mixed> $modifiers = [] ]) : Cosmo

Use Cosmo::fromAcceptLanguage() — renamed for parity with the cosmo-js port.

Parameters
$header : string|null = null
$modifiers : array<string|int, mixed> = []
Return values
Cosmo

createFromSubtags()

public static createFromSubtags(array<string|int, mixed> $subtags[, array<string|int, mixed> $modifiers = [] ]) : Cosmo

Use Cosmo::fromSubtags() — renamed for parity with the cosmo-js port.

Parameters
$subtags : array<string|int, mixed>
$modifiers : array<string|int, mixed> = []
Return values
Cosmo

currency()

Returns the localised name or symbol of a currency.

public currency([string|null|Sentinel $currencyCode = Sentinel::Unset ][, bool $getSymbol = false ][, bool $strict = false ]) : string
Parameters
$currencyCode : string|null|Sentinel = Sentinel::Unset

ISO 4217 currency code, e.g. 'AUD'. Defaults to the locale's currency.

$getSymbol : bool = false

Return the standard currency symbol (e.g. 'A$') instead of the full name. This is the disambiguated symbol — matches the cosmo-js port's currencyDisplay:"symbol" (not the ambiguous narrow form).

$strict : bool = false

Throw if the currency code is invalid instead of returning it as-is.

Tags
throws
Exception

If $strict is true and the currency code is not recognised.

Return values
string

date()

Formats a date value (no time component).

public date(mixed $value[, string $width = 'short' ]) : string
Parameters
$value : mixed

A DateTimeInterface, IntlCalendar, Unix timestamp, or localtime() array.

$width : string = 'short'

Format width: 'none', 'short', 'medium', 'long', or 'full'.

Return values
string

dateRange()

Formats a date or time range using CLDR interval format patterns (e.g. "Feb 2 – 5, 2020").

public dateRange(mixed $start, mixed $end[, string $dateWidth = 'medium' ][, string $timeWidth = 'none' ]) : string

Elements shared by both endpoints (year, month) are elided.

Backed by ICU's CLDR intervalFormats resource — no hardcoded locale data. PHP's intl extension does not bind ICU's DateIntervalFormat, so this reads the interval pattern for the greatest-differing field from the ResourceBundle, splits it where the repeated field recurs, and formats each half with IntlDateFormatter.

Only the 'short' and 'medium' widths are supported: CLDR carries no long/full interval skeletons, and ICU's own derivation of them is unavailable through ext-intl. Supported combinations:

  • Date-only: (short|medium, 'none') → e.g. "Feb 2 – 5, 2020"
  • Time-only: ('none', short|medium) → e.g. "3:00 – 5:30 PM" When a locale's interval table lacks the differing field, the two endpoints are joined with the locale's range separator without elision (still correct output).
Parameters
$start : mixed

Start of the range (DateTimeInterface, IntlCalendar, Unix timestamp, or localtime() array).

$end : mixed

End of the range.

$dateWidth : string = 'medium'

Date component width: 'none', 'short', or 'medium'.

$timeWidth : string = 'none'

Time component width: 'none', 'short', or 'medium'.

Tags
throws
Exception

If $dateWidth or $timeWidth is 'long'/'full' or otherwise invalid.

Return values
string

direction()

Returns the text direction of a language: 'rtl' or 'ltr'.

public direction([string|null|Sentinel $language = Sentinel::Unset ]) : string
Parameters
$language : string|null|Sentinel = Sentinel::Unset

BCP 47 language code. Defaults to the instance locale.

Return values
string

'rtl' or 'ltr'.

displayName()

Generic localised display name — a single entry point over the dedicated lookups.

public displayName(string $type, string $code) : string
Parameters
$type : string

'language', 'region', 'script', 'calendar', or 'currency'.

$code : string

The code to translate (e.g. 'en', 'AU', 'Hans', 'buddhist', 'EUR').

Tags
throws
Exception

If $type is not recognised.

Return values
string

duration()

Formats an undirected duration.

public duration(float|array<string|int, mixed> $duration[, bool $withWords = false ]) : string
Parameters
$duration : float|array<string|int, mixed>

A number of seconds (rendered as the "339:17:20" clock form), or an array of units — ['hours' => 3, 'minutes' => 5] — for multi-unit output ("3 hours, 5 minutes"). Accepted units: years, months, weeks, days, hours, minutes, seconds, milliseconds.

$withWords : bool = false

Scalar form → spell the units out (English only); array form → wide units (vs the abbreviated default).

Return values
string

ellipsize()

Truncates text to at most $max graphemes, breaking on a word boundary and appending $ellipsis. Grapheme-aware, so it never splits a combining sequence. Returns the original text if it already fits.

public ellipsize(string $text, int $max[, string $ellipsis = '…' ]) : string
Parameters
$text : string
$max : int
$ellipsis : string = '…'
Return values
string

formatMoment()

Formats a date/time value using a custom ICU pattern.

public formatMoment(mixed $value, string $pattern[, string|null $calendar = null ]) : string
Parameters
$value : mixed

A DateTimeInterface, IntlCalendar, Unix timestamp (int/float), or localtime() array.

$pattern : string

ICU date/time pattern, e.g. 'YYYY-MM-dd'.

$calendar : string|null = null

Pass 'gregorian' to force the Gregorian calendar. Defaults to the locale's native calendar.

Tags
throws
Exception

If the value cannot be formatted.

Return values
string

fromAcceptLanguage()

Creates a Cosmo instance from an HTTP Accept-Language header.

public static fromAcceptLanguage([string|null $header = null ][, array<string|int, mixed> $modifiers = [] ]) : Cosmo
Parameters
$header : string|null = null

Accept-Language header value. Defaults to $_SERVER['HTTP_ACCEPT_LANGUAGE'].

$modifiers : array<string|int, mixed> = []

Optional overrides: 'calendar', 'currency', 'timeZone'.

Return values
Cosmo

fromSubtags()

Creates a Cosmo instance from an array of locale subtags instead of a locale string.

public static fromSubtags(array<string|int, mixed> $subtags[, array<string|int, mixed> $modifiers = [] ]) : Cosmo
Parameters
$subtags : array<string|int, mixed>

Locale subtag array, e.g. ['language' => 'en', 'region' => 'AU'].

$modifiers : array<string|int, mixed> = []

Optional overrides: 'calendar', 'currency', 'timeZone'.

Tags
see
Locale::composeLocale()

for the expected array format.

Return values
Cosmo

get()

Retrieves a value from an ICU resource bundle, falling back to the primary language then root.

public get(string $bundleName, string ...$path) : ResourceBundle|int|array<string|int, mixed>|string|null
Parameters
$bundleName : string

ICU bundle name, e.g. Bundle::LOCALE.

$path : string

One or more keys to traverse into the bundle.

Return values
ResourceBundle|int|array<string|int, mixed>|string|null

join()

Joins a list using the locale's conventions (e.g. "A, B, and C"). Built from CLDR listPattern data — PHP reaches ICU directly, so no Intl.ListFormat is needed.

public join(array<string|int, mixed> $items[, string $type = 'conjunction' ][, string $width = 'full' ]) : string
Parameters
$items : array<string|int, mixed>

The items to join.

$type : string = 'conjunction'

'conjunction' (and, default), 'disjunction' (or), or 'unit'.

$width : string = 'full'

'none'/'long'/'full' (wide), 'medium' (short), or 'short' (narrow).

Tags
throws
Exception

If $type or $width is not valid.

Return values
string

language()

Returns the localised name of a language (e.g. 'en' -> 'English', 'glk' -> 'Gilaki').

public language([string|null|Sentinel $language = Sentinel::Unset ]) : string

If you have a full locale identifier (e.g. en_AU), pass it through Locale::getPrimaryLanguage() first.

Parameters
$language : string|null|Sentinel = Sentinel::Unset

BCP 47 language code. Defaults to the instance locale.

Return values
string

Empty string if the language is null or empty.

lower()

Locale-aware lower-casing.

public lower(string $text) : string
Parameters
$text : string
Return values
string

message()

Formats an ICU message string with the given arguments.

public message(string $pattern[, array<string|int, mixed> $args = [] ]) : string
Parameters
$pattern : string

ICU message pattern, e.g. '{0, plural, one {# item} other {# items}'.

$args : array<string|int, mixed> = []

Arguments to substitute into the pattern.

Return values
string

moment()

Formats a date, time, or date+time value using the locale's conventions.

public moment(mixed $value[, string $dateWidth = 'short' ][, string $timeWidth = 'short' ][, string|null $calendar = null ][, string|null $pattern = null ]) : string
Parameters
$value : mixed

A DateTimeInterface, IntlCalendar, Unix timestamp (int/float), or localtime() array.

$dateWidth : string = 'short'

Date format: 'none', 'short', 'medium', 'long', or 'full'.

$timeWidth : string = 'short'

Time format: 'none', 'short', 'medium', 'long', or 'full'.

$calendar : string|null = null

Pass 'gregorian' to force the Gregorian calendar regardless of locale. Defaults to the locale's native calendar (e.g. Persian for fa_IR).

$pattern : string|null = null

Optional ICU date/time pattern, overrides $dateWidth/$timeWidth when set.

Tags
throws
Exception

If the value cannot be formatted.

Return values
string

money()

Formats a monetary value using the locale's currency format.

public money(float $value[, string|null $currency = null ][, int|null $precision = null ][, bool $strict = false ][, string $pattern = '' ][, array<string|int, mixed> $options = [] ]) : string

The shared parameters ($value, $currency, $precision, $strict) line up with the cosmo-js port's money(value, code, {precision, strict}); $pattern is a PHP-only extra (the Intl API exposes no NumberFormatter pattern) and is therefore last.

Parameters
$value : float

The amount to format.

$currency : string|null = null

ISO 4217 currency code, e.g. 'AUD'. Defaults to the locale's currency.

$precision : int|null = null

Number of decimal digits. Defaults to the currency's standard precision.

$strict : bool = false

Throw if no currency is available instead of returning an empty string.

$pattern : string = ''

Optional NumberFormatter pattern to override the default format (PHP-only).

$options : array<string|int, mixed> = []
Tags
throws
Exception

If $strict is true and no currency code is set.

Return values
string

moneyRange()

Formats a monetary range (e.g. "$3.00–$5.00"). Returns '' when no currency is available. Like numberRange(), an approximation of ICU's NumberRangeFormatter.

public moneyRange(float $start, float $end[, string|null $code = null ]) : string
Parameters
$start : float
$end : float
$code : string|null = null

ISO 4217 code; defaults to the locale/region currency.

Return values
string

monthNames()

Localised month names (January … December), following the active calendar.

public monthNames([string $width = 'full' ]) : array<string|int, string>
Parameters
$width : string = 'full'

'none'/'long'/'full' (wide), 'medium' (abbreviated), or 'short' (narrow).

Tags
throws
Exception

If $width is not valid.

Return values
array<string|int, string>

number()

Formats a number using the locale's default number format.

public number(float $number[, array<string|int, mixed> $options = [] ]) : string
Parameters
$number : float
$options : array<string|int, mixed> = []

Optional number-formatting controls: 'minimumIntegerDigits', 'minimumFractionDigits', 'maximumFractionDigits', 'minimumSignificantDigits', 'maximumSignificantDigits', 'roundingMode' (ceil/floor/expand/trunc/halfExpand/halfTrunc/halfEven), 'roundingIncrement', 'useGrouping'. Portable across the JS and Python ports. The JS-only options ('signDisplay', 'trailingZeroDisplay', 'roundingPriority', 'notation', 'compactDisplay') have no equivalent in ICU's NumberFormatter and are ignored.

Return values
string

numberRange()

Formats a numeric range (e.g. "3–5"). Built from the CLDR `range` pattern ("{0}–{1}") since ext-intl binds no NumberRangeFormatter; unlike ICU's formatter it does not collapse shared parts (always "3–5", never "3–5K").

public numberRange(float $start, float $end) : string
Parameters
$start : float
$end : float
Return values
string

ordinal()

Formats a number as a localised ordinal (e.g. 1 -> '1st' in English).

public ordinal(int $number) : string
Parameters
$number : int
Return values
string

parseDate()

Parses a localised date written at the given width. The inverse of date().

public parseDate(string $text[, string $width = 'short' ]) : DateTimeImmutable
Parameters
$text : string
$width : string = 'short'

'short', 'medium', 'long', or 'full'.

Tags
throws
Exception

If the text does not match the locale's date format.

Return values
DateTimeImmutable

The parsed moment (UTC).

parseMoment()

Parses a moment with a raw ICU pattern. The inverse of formatMoment().

public parseMoment(string $text, string $pattern) : DateTimeImmutable
Parameters
$text : string
$pattern : string
Tags
throws
Exception

If the text does not match the pattern.

Return values
DateTimeImmutable

The parsed moment (UTC).

parseMoney()

Parses a localised monetary string ('$12.30' -> amount 12.3, currency USD).

public parseMoney(string $text) : array{amount: float, currency: string}

The inverse of money().

Parameters
$text : string
Tags
throws
Exception

If the text is not a monetary value in this locale.

Return values
array{amount: float, currency: string}

parseNumber()

Parses a localised number ('1.234,56' in de -> 1234.56). The inverse of number().

public parseNumber(string $text) : float
Parameters
$text : string
Tags
throws
Exception

If the text is not a number in this locale.

Return values
float

percentage()

Formats a decimal value as a localised percentage (e.g. 0.2 -> '20%').

public percentage(float $value[, int $precision = 3 ][, array<string|int, mixed> $options = [] ]) : string
Parameters
$value : float

Decimal value, e.g. 0.2 for 20%.

$precision : int = 3

Maximum number of decimal digits.

$options : array<string|int, mixed> = []
Return values
string

pluralCategory()

The LDML plural category a number falls into for this locale (e.g. 1 -> 'one', 2 -> 'other' in English). Derived from ICU's plural rules via MessageFormatter (PHP's intl exposes no PluralRules class).

public pluralCategory(int|float $value[, bool $ordinal = false ]) : string
Parameters
$value : int|float

The number to categorise.

$ordinal : bool = false

Use ordinal rules (1st/2nd/3rd …) instead of cardinal.

Return values
string

One of 'zero', 'one', 'two', 'few', 'many', 'other'.

precision()

Formats a number with a fixed number of fraction digits — always exactly $fractionDigits, padding with trailing zeros and rounding as needed. Use it when you want 1 to render as '1.00' and 1.002 to stay '1.00', never '1.0'.

public precision(float $value[, int $fractionDigits = 2 ][, array<string|int, mixed> $options = [] ]) : string

Pass an $options bag (see number()) to widen the band — e.g. ['maximumFractionDigits' => 3] — or tweak rounding/grouping.

Parameters
$value : float
$fractionDigits : int = 2

Fixed fraction digits (sets both the min and the max); defaults to 2.

$options : array<string|int, mixed> = []

Optional number-formatting controls.

Return values
string

quote()

Wraps a string in the locale's quotation marks (e.g. "text" in English, «text» in Persian).

public quote(string $quote) : string
Parameters
$quote : string

The text to quote.

Return values
string

relativeDuration()

Renders a directed (signed) duration in words: (-3, 'day') -> "3 days ago", (2, 'hour') -> "in 2 hours". The directed counterpart of duration().

public relativeDuration(int|float $amount, string $unit[, string $numeric = 'always' ]) : string

Reconstructed from CLDR fields data (ext-intl binds no RelativeDateTimeFormatter). With $numeric = 'auto', exact -1/0/1 offsets use the locale's word forms ("yesterday", "today", "tomorrow") where CLDR provides them.

Parameters
$amount : int|float

Signed: negative = past ("… ago"), positive = future ("in …").

$unit : string

second, minute, hour, day, week, month, quarter, or year.

$numeric : string = 'always'

'always' (default, "1 day ago") or 'auto' ("yesterday").

Tags
throws
Exception

If $unit is not a valid relative unit.

Return values
string

relativeDurationBetween()

Renders the directed duration between two moments as relative text, picking the largest sensible unit (e.g. "in 5 days", "3 days ago"). Computes target − reference.

public relativeDurationBetween(mixed $target[, mixed|null $reference = null ][, string $numeric = 'auto' ]) : string
Parameters
$target : mixed

The moment being described (DateTimeInterface, IntlCalendar, Unix timestamp, or localtime() array).

$reference : mixed|null = null

The moment to measure against; defaults to now.

$numeric : string = 'auto'

'auto' (default, allows "yesterday") or 'always'.

Return values
string

removeLikelySubtags()

Returns a new Cosmo with likely subtags removed (e.g. "en_Latn_US" → "en").

public removeLikelySubtags() : static

CLDR algorithm: keep the shortest of language / language_region / language_script that still maximises to the same locale.

Return values
static

romanize()

Romanises text ('Москва' -> 'Moskva'); shorthand for the 'Any-Latin' transform.

public romanize(string $text) : string
Parameters
$text : string
Return values
string

scientific()

Scientific notation (e.g. 12345 -> "1.2345E4").

public scientific(float $value) : string
Parameters
$value : float
Return values
string

script()

Returns the localised name of a script (e.g. 'Hans' -> 'Simplified Chinese').

public script([string|null|Sentinel $script = Sentinel::Unset ]) : string

If omitted, uses the script subtag from the instance locale if present.

Parameters
$script : string|null|Sentinel = Sentinel::Unset

ISO 15924 script code. Defaults to the locale's script subtag.

Return values
string

sort()

Returns a new array sorted by the locale's collation rules.

public sort(iterable<string|int, mixed> $items[, callable|null $key = null ][, array<string|int, mixed> $options = [] ]) : array<string|int, mixed>
Parameters
$items : iterable<string|int, mixed>

The items to sort.

$key : callable|null = null

Optional accessor returning the string to sort each item by.

$options : array<string|int, mixed> = []
Return values
array<string|int, mixed>

spellout()

Spells out a number in the locale's language (e.g. 42 -> 'forty-two' in English).

public spellout(float $number) : string
Parameters
$number : float
Return values
string

splitGraphemes()

Splits text into grapheme clusters (user-perceived characters), so combining marks and emoji ZWJ sequences stay intact.

public splitGraphemes(string $text) : array<string|int, string>
Parameters
$text : string
Return values
array<string|int, string>

splitSentences()

Splits text into sentences using the locale's sentence-boundary rules.

public splitSentences(string $text) : array<string|int, string>
Parameters
$text : string
Return values
array<string|int, string>

splitWords()

Splits text into words using the locale's word-boundary rules, keeping only word-like segments (drops whitespace and punctuation).

public splitWords(string $text) : array<string|int, string>
Parameters
$text : string
Return values
array<string|int, string>

supportedValues()

The values the runtime's ICU supports for a given key. PHP's intl surface enumerates 'timeZone' (IntlTimeZone), 'currency' (CLDR currency bundle) and 'transliterator' (Transliterator::listIDs); other keys ('calendar', 'collation', 'numberingSystem', 'unit') are not reachable through it and raise rather than return a hardcoded list.

public supportedValues(string $key) : array<string|int, string>
Parameters
$key : string

'timeZone', 'currency', or 'transliterator'.

Tags
throws
Exception

If $key is not supported.

Return values
array<string|int, string>

suspicious()

Whether a string fails ICU's default spoof checks (mixed scripts, restriction level, invisible characters) per UTS #39.

public suspicious(string $text) : bool
Parameters
$text : string
Return values
bool

symbol()

Returns a localised number symbol (e.g. 'decimal', 'group', 'percent').

public symbol(int|string $symbol) : string

Accepts a NumberFormatter symbol constant, or a case-insensitive name. The short names match the JS and Python ports ('decimal', 'group', 'minus', 'plus', …); the full constant names ('decimal_separator', 'minus_sign', …) and the _symbol/_separator/_sign suffixes are accepted too.

Parameters
$symbol : int|string

NumberFormatter symbol constant or string name.

Tags
throws
Exception

If the string name does not match a known symbol.

Return values
string

time()

Formats a time value (no date component).

public time(mixed $value[, string $width = 'short' ]) : string
Parameters
$value : mixed

A DateTimeInterface, IntlCalendar, Unix timestamp, or localtime() array.

$width : string = 'short'

Format width: 'none', 'short', 'medium', 'long', or 'full'.

Return values
string

timeZoneName()

Localised display name of a time zone (e.g. "Australian Eastern Standard Time").

public timeZoneName([string $style = 'long' ]) : string

Defaults to the 'timeZone' modifier, falling back to the runtime zone.

Parameters
$style : string = 'long'

'long' (default), 'short', 'shortOffset', 'longOffset', 'shortGeneric', or 'longGeneric'.

Tags
throws
Exception

If $style is not valid.

Return values
string

transliterate()

Runs an ICU transform over the text — script conversion, romanisation, accent folding ('Any-Latin; Latin-ASCII' makes ASCII slugs).

public transliterate(string $text, string $id) : string
Parameters
$text : string
$id : string

A compound ICU transliterator id; see supportedValues('transliterator') for the building blocks.

Tags
throws
Exception

If $id is not a valid transliterator id.

Return values
string

unit()

Formats a measurement value with a localised unit (e.g. 2.19 gigabytes, 26 degrees Celsius).

public unit(string $category, string $unit, float|int $value[, string $width = 'full' ]) : string
Parameters
$category : string

Unit category, e.g. 'digital', 'temperature', 'mass'.

$unit : string

Unit within the category, e.g. 'gigabyte', 'celsius', 'gram'.

$value : float|int

The numeric value to format.

$width : string = 'full'

Format width: 'short', 'medium', 'long', or 'full'.

Tags
throws
Exception

If $width is not a valid format width.

see
https://intl.rmcreative.ru/site/unit-data?locale=en

for available units and scales.

Return values
string

upper()

Locale-aware upper-casing (e.g. Turkish dotted/dotless I). Falls back to the language-neutral ICU casing when the locale has no special rules.

public upper(string $text) : string
Parameters
$text : string
Return values
string

weekdayNames()

Localised weekday names, Sunday first (matching ICU symbol order).

public weekdayNames([string $width = 'full' ]) : array<string|int, string>
Parameters
$width : string = 'full'

'none'/'long'/'full' (wide), 'medium' (abbreviated), or 'short' (narrow).

Tags
throws
Exception

If $width is not valid.

Return values
array<string|int, string>

weekInfo()

Week conventions for the locale: first day of the week, weekend days, and the minimal days in the first week. Days are 1 = Monday … 7 = Sunday (ISO 8601), matching the cosmo-js port.

public weekInfo() : array{firstDay: int, weekend: int[], minimalDays: int}
Return values
array{firstDay: int, weekend: int[], minimalDays: int}

applyCollationOptions()

Applies portable collation tailoring ('numeric', 'caseFirst') to a Collator.

private applyCollationOptions(Collator $collator, array<string|int, mixed> $options) : void
Parameters
$collator : Collator
$options : array<string|int, mixed>

applyListPattern()

private applyListPattern(string $pattern, string $first, string $second) : string
Parameters
$pattern : string
$first : string
$second : string
Return values
string

applyNumberOptions()

Applies a portable NumberOptions array to a NumberFormatter.

private applyNumberOptions(NumberFormatter $formatter, array<string|int, mixed> $options) : void

JS-only options ('signDisplay', 'trailingZeroDisplay', 'roundingPriority', 'notation', 'compactDisplay') have no equivalent in ICU's legacy NumberFormatter and are silently ignored here, matching the documented contract.

Parameters
$formatter : NumberFormatter
$options : array<string|int, mixed>

bundleToPluralMessage()

private bundleToPluralMessage(ResourceBundle $bundle) : string
Parameters
$bundle : ResourceBundle
Return values
string

durationParts()

Renders a multi-unit duration by formatting each unit with unit() and joining them with the locale's CLDR unit-list pattern (PHP's intl has no MeasureFormat).

private durationParts(array<string|int, mixed> $parts, bool $withWords) : string
Parameters
$parts : array<string|int, mixed>
$withWords : bool
Return values
string

extract()

private extract(mixed $locale, mixed $bundleName, array<string|int, mixed> $path) : ResourceBundle|int|array<string|int, mixed>|string|null
Parameters
$locale : mixed
$bundleName : mixed
$path : array<string|int, mixed>
Return values
ResourceBundle|int|array<string|int, mixed>|string|null

getWidth()

private getWidth(string $width) : int
Parameters
$width : string
Return values
int

isRtlScript()

Whether an ISO 15924 script is written right-to-left, derived live from ICU's Unicode property data: the bidi class of the script's first strong character.

private static isRtlScript(string $script) : bool

(ext-intl exposes no Script::isRightToLeft(), unlike PyICU and Intl.Locale; composite scripts with no direct codepoints, e.g. Jpan, resolve to LTR.)

Parameters
$script : string
Return values
bool

listPattern()

Resolves one CLDR list-pattern piece ('2', 'start', 'middle', 'end'), falling back from the width-specific variant to the base type to 'standard'. Each lookup goes through get() so a partial locale override (e.g. en_AU defines only 'end' for 'standard') still inherits the remaining pieces from the parent locale.

private listPattern(string $key, string $suffix, string $piece) : string
Parameters
$key : string
$suffix : string
$piece : string
Return values
string

maximiseSubtags()

Maximised ['language', 'script', 'region'] for a locale per the CLDR likely-subtags algorithm (UTS #35), resolved against ICU's likelySubtags table, or null when nothing matches. Subtags present in the source always win; only missing ones are filled from the table (so az → az_Latn_AZ but az_IQ → az_Arab_IQ, and an explicit script like ar_Latn is never replaced).

private static maximiseSubtags(string $locale) : array<string|int, mixed>|null
Parameters
$locale : string
Return values
array<string|int, mixed>|null

nameWidth()

private nameWidth(string $width) : int
Parameters
$width : string
Return values
int

rangePattern()

The locale's CLDR number range pattern ("{0}–{1}"), falling back to root's.

private rangePattern() : string
Return values
string

replaceCoreSubtags()

Rebuilds a locale ID with new core language/script/region subtags while preserving its variants and any @keyword extensions, which parseLocale/ composeLocale would otherwise drop.

private static replaceCoreSubtags(string $locale, array<string|int, mixed> $core) : string
Parameters
$locale : string
$core : array<string|int, mixed>
Return values
string

splitIntervalPattern()

Split a CLDR interval format pattern into its start and end sub-patterns.

private static splitIntervalPattern(string $pattern) : array<string|int, mixed>

An interval pattern lays out both endpoints back to back and repeats one field, e.g. "MMM d – d, y" or "E, MMM d – E, MMM d, y". The second endpoint begins at the first pattern letter that has already appeared earlier (ICU's own rule), so everything before that — including the locale's separator — belongs to the first endpoint. This needs no separator data, so it is robust to CLDR quirks like the Spanish " al " separator or Bosnian's fallback/​pattern hyphen-vs-dash mismatch.

Examples: splitIntervalPattern("MMM d – d, y") → ["MMM d – ", "d, y"] splitIntervalPattern("d.–d. MMM y") → ["d.–", "d. MMM y"] splitIntervalPattern("E, MMM d – E, MMM d, y") → ["E, MMM d – ", "E, MMM d, y"]

Parameters
$pattern : string
Return values
array<string|int, mixed>

toTimestampMs()

Convert a mixed date/time value to a Unix timestamp in milliseconds (for IntlCalendar::setTime()).

private static toTimestampMs(mixed $value) : float
Parameters
$value : mixed
Return values
float
On this page

Search results