English | 简体中文 | 繁體中文
查询

MessageFormatter::parseMessage()函数—用法及示例

「 将一个格式化的消息解析为具体的值,并返回解析后的结果 」


函数名称:MessageFormatter::parseMessage()

适用版本:PHP 5 >= 5.3.0, PHP 7, PHP 8

函数描述:MessageFormatter::parseMessage() 函数将一个格式化的消息解析为具体的值,并返回解析后的结果。

用法:

MessageFormatter::parseMessage(string $locale, string $pattern, string $message)

参数:

  • $locale:表示语言环境的字符串,例如 'en_US' 或 'zh_CN'。
  • $pattern:表示消息格式的字符串,其中包含占位符和格式化选项。
  • $message:要解析的格式化消息字符串。

返回值:

  • 如果解析成功,返回一个包含解析结果的数组。
  • 如果解析失败,则返回 FALSE。

示例:

$locale = 'en_US';
$pattern = 'Hi {name}, the weather is {weather}.';
$message = 'Hi John, the weather is sunny.';

$result = MessageFormatter::parseMessage($locale, $pattern, $message);

print_r($result);

输出:

Array
(
    [name] => John
    [weather] => sunny
)

在上面的示例中,我们使用了英文语言环境('en_US'),并定义了一个格式化消息模式('Hi {name}, the weather is {weather}.')。然后,我们将一个具体的格式化消息('Hi John, the weather is sunny.')传递给 MessageFormatter::parseMessage() 函数进行解析。解析结果是一个数组,其中包含了占位符的具体值。在这个例子中,占位符 {name} 被解析为 'John',占位符 {weather} 被解析为 'sunny'。

补充纠错
热门PHP函数
分享链接