PHP函式:MessageFormatter::format()
適用版本:PHP 5 >= 5.3.0, PHP 7
函式用法: MessageFormatter::format()函式用於根據給定的模板和引數格式化訊息。它使用 ICU MessageFormat 格式規範來建立可本地化的訊息。
函式語法: string MessageFormatter::format(string $locale, string $pattern, array $args)
引數說明:
- $locale:可選引數,表示要使用的語言環境。如果未指定,則使用預設語言環境。
- $pattern:表示要格式化的訊息模板。模板可以包含佔位符,用於插入引數值。
- $args:表示要插入到訊息模板中的引數陣列。
返回值: 返回格式化後的訊息字串。
示例用法:
$locale = 'en_US';
$pattern = 'Hello, {0}! You have {1, number} messages.';
$args = ['John', 5];
$message = MessageFormatter::format($locale, $pattern, $args);
echo $message;
輸出結果: Hello, John! You have 5 messages.
在上面的示例中,我們使用英文美國語言環境(en_US)和給定的模板來格式化訊息。模板中的佔位符 {0} 和 {1, number} 分別被陣列中的引數 'John' 和 5 替換,最終得到格式化後的訊息字串。