查詢

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函式
分享連結