牛牛在线工具

MessageFormatter::formatMessage()

收录 8868 个 PHP 函数,含用途说明与用法示例。

MessageFormatter::formatMessage()

根据给定的消息模板和参数格式化消息

函数名:MessageFormatter::formatMessage() 适用版本:PHP 5 >= 5.3.0, PHP 7 用法: MessageFormatter::formatMessage() 函数用于根据给定的消息模板和参数格式化消息。它使用 ICU 消息格式来支持多语言和复杂的消息格式化。 语法: public static string MessageFormatter::formatMessage(string $locale, string $pattern, array $args): string 参数: $locale:要使用的区域设置(例如:"en_US")。 $pattern:消息模板,它可以包含占位符来插入参数。 $args:包含要插入到消息中的参数的数组。 返回值: 返回格式化后的消息字符串。 示例: $locale = 'en_US'; $pattern = 'Hello, {0}! You have {1, number} messages.'; $args = ['John', 42]; $message = MessageFormatter::formatMessage($locale, $pattern, $args); echo $message; 输出: Hello, John! You have 42 messages. 解释: 在上面的示例中,我们使用英文美国区域设置(en_US)和消息模板("Hello, {0}! You have {1, number} messages.")来格式化消息。消息模板中的 {0} 和 {1, number} 是占位符,分别表示第一个和第二个参数。在 $args 数组中,我们提供了两个参数值,分别是 'John' 和 42。最终,调用 MessageFormatter::formatMessage() 函数会将参数插入到模板中,并返回格式化后的消息字符串。在这个例子中,输出的消息是 "Hello, John! You have 42 messages."。