예제 #1
0
 /**
  * Parses an input string according to an [ICU message format](http://userguide.icu-project.org/formatparse/messages) pattern.
  *
  * It uses the PHP intl extension's [MessageFormatter::parse()](http://www.php.net/manual/en/messageformatter.parsemessage.php)
  * and adds support for named arguments.
  * Usage of this method requires PHP intl extension to be installed.
  *
  * @param string $pattern The pattern to use for parsing the message.
  * @param string $message The message to parse, conforming to the pattern.
  * @param string $language The locale to use for formatting locale-dependent parts
  * @return array|boolean An array containing items extracted, or `FALSE` on error.
  * @throws \yii\base\NotSupportedException when PHP intl extension is not installed.
  */
 public function parse($pattern, $message, $language)
 {
     $this->_errorCode = 0;
     $this->_errorMessage = '';
     if (!class_exists('MessageFormatter', false)) {
         throw new NotSupportedException('You have to install PHP intl extension to use this feature.');
     }
     // replace named arguments
     if (($tokens = self::tokenizePattern($pattern)) === false) {
         $this->_errorCode = -1;
         $this->_errorMessage = "Message pattern is invalid.";
         return false;
     }
     $map = [];
     foreach ($tokens as $i => $token) {
         if (is_array($token)) {
             $param = trim($token[0]);
             if (!isset($map[$param])) {
                 $map[$param] = count($map);
             }
             $token[0] = $map[$param];
             $tokens[$i] = '{' . implode(',', $token) . '}';
         }
     }
     $pattern = implode('', $tokens);
     $map = array_flip($map);
     $formatter = new \MessageFormatter($language, $pattern);
     if ($formatter === null) {
         $this->_errorCode = -1;
         $this->_errorMessage = "Message pattern is invalid.";
         return false;
     }
     $result = $formatter->parse($message);
     if ($result === false) {
         $this->_errorCode = $formatter->getErrorCode();
         $this->_errorMessage = $formatter->getErrorMessage();
         return false;
     } else {
         $values = [];
         foreach ($result as $key => $value) {
             $values[$map[$key]] = $value;
         }
         return $values;
     }
 }
예제 #2
0
<?php

ini_set("intl.error_level", E_WARNING);
date_default_timezone_set('Europe/Lisbon');
//ignored for now, see bug #58756
$d = 1336308097.123;
$mf = new MessageFormatter('en_US', "On {0,time,yyyy-MM-dd G 'at' HH:mm:ss.SSS zzz} something odd happened");
var_dump($mf->format(array(1336310569.123)));
$p = 'On 2012-05-06 AD at 15:22:49.123 GMT+02:00 something odd happened';
var_dump($mf->parse($p));
?>
==DONE==