Best Atoum code snippet using locale.format
Format.php
Source:Format.php
...32 */33class Zend_Locale_Format34{35 const STANDARD = 'auto';36 private static $_options = array('date_format' => null,37 'number_format' => null,38 'format_type' => 'iso',39 'fix_date' => false,40 'locale' => null,41 'cache' => null,42 'disableCache' => null,43 'precision' => null);44 /**45 * Sets class wide options, if no option was given, the actual set options will be returned46 * The 'precision' option of a value is used to truncate or stretch extra digits. -1 means not to touch the extra digits.47 * The 'locale' option helps when parsing numbers and dates using separators and month names.48 * The date format 'format_type' option selects between CLDR/ISO date format specifier tokens and PHP's date() tokens.49 * The 'fix_date' option enables or disables heuristics that attempt to correct invalid dates.50 * The 'number_format' option can be used to specify a default number format string51 * The 'date_format' option can be used to specify a default date format string, but beware of using getDate(),52 * checkDateFormat() and getTime() after using setOptions() with a 'format'. To use these four methods53 * with the default date format for a locale, use array('date_format' => null, 'locale' => $locale) for their options.54 *55 * @param array $options Array of options, keyed by option name: format_type = 'iso' | 'php', fix_date = true | false,56 * locale = Zend_Locale | locale string, precision = whole number between -1 and 3057 * @throws Zend_Locale_Exception58 * @return array if no option was given59 */60 public static function setOptions(array $options = array())61 {62 self::$_options = self::_checkOptions($options) + self::$_options;63 return self::$_options;64 }65 /**66 * Internal function for checking the options array of proper input values67 * See {@link setOptions()} for details.68 *69 * @param array $options Array of options, keyed by option name: format_type = 'iso' | 'php', fix_date = true | false,70 * locale = Zend_Locale | locale string, precision = whole number between -1 and 3071 * @throws Zend_Locale_Exception72 * @return array if no option was given73 */74 private static function _checkOptions(array $options = array())75 {76 if (count($options) == 0) {77 return self::$_options;78 }79 foreach ($options as $name => $value) {80 $name = strtolower($name);81 if ($name !== 'locale') {82 if (gettype($value) === 'string') {83 $value = strtolower($value);84 }85 }86 switch($name) {87 case 'number_format' :88 if ($value == Zend_Locale_Format::STANDARD) {89 $locale = self::$_options['locale'];90 if (isset($options['locale'])) {91 $locale = $options['locale'];92 }93 $options['number_format'] = Zend_Locale_Data::getContent($locale, 'decimalnumber');94 } else if ((gettype($value) !== 'string') and ($value !== NULL)) {95 #require_once 'Zend/Locale/Exception.php';96 $stringValue = (string)(is_array($value) ? implode(' ', $value) : $value);97 throw new Zend_Locale_Exception("Unknown number format type '" . gettype($value) . "'. "98 . "Format '$stringValue' must be a valid number format string.");99 }100 break;101 case 'date_format' :102 if ($value == Zend_Locale_Format::STANDARD) {103 $locale = self::$_options['locale'];104 if (isset($options['locale'])) {105 $locale = $options['locale'];106 }107 $options['date_format'] = Zend_Locale_Format::getDateFormat($locale);108 } else if ((gettype($value) !== 'string') and ($value !== NULL)) {109 #require_once 'Zend/Locale/Exception.php';110 $stringValue = (string)(is_array($value) ? implode(' ', $value) : $value);111 throw new Zend_Locale_Exception("Unknown dateformat type '" . gettype($value) . "'. "112 . "Format '$stringValue' must be a valid ISO or PHP date format string.");113 } else {114 if (((isset($options['format_type']) === true) and ($options['format_type'] == 'php')) or115 ((isset($options['format_type']) === false) and (self::$_options['format_type'] == 'php'))) {116 $options['date_format'] = Zend_Locale_Format::convertPhpToIsoFormat($value);117 }118 }119 break;120 case 'format_type' :121 if (($value != 'php') && ($value != 'iso')) {122 #require_once 'Zend/Locale/Exception.php';123 throw new Zend_Locale_Exception("Unknown date format type '$value'. Only 'iso' and 'php'"124 . " are supported.");125 }126 break;127 case 'fix_date' :128 if (($value !== true) && ($value !== false)) {129 #require_once 'Zend/Locale/Exception.php';130 throw new Zend_Locale_Exception("Enabling correction of dates must be either true or false"131 . "(fix_date='$value').");132 }133 break;134 case 'locale' :135 $options['locale'] = Zend_Locale::findLocale($value);136 break;137 case 'cache' :138 if ($value instanceof Zend_Cache_Core) {139 Zend_Locale_Data::setCache($value);140 }141 break;142 case 'disablecache' :143 if (null !== $value) {144 Zend_Locale_Data::disableCache($value);145 }146 break;147 case 'precision' :148 if ($value === NULL) {149 $value = -1;150 }151 if (($value < -1) || ($value > 30)) {152 #require_once 'Zend/Locale/Exception.php';153 throw new Zend_Locale_Exception("'$value' precision is not a whole number less than 30.");154 }155 break;156 default:157 #require_once 'Zend/Locale/Exception.php';158 throw new Zend_Locale_Exception("Unknown option: '$name' = '$value'");159 break;160 }161 }162 return $options;163 }164 /**165 * Changes the numbers/digits within a given string from one script to another166 * 'Decimal' representated the stardard numbers 0-9, if a script does not exist167 * an exception will be thrown.168 *169 * Examples for conversion from Arabic to Latin numerals:170 * convertNumerals('١١٠Tests', 'Arab'); -> returns '100 Tests'171 * Example for conversion from Latin to Arabic numerals:172 * convertNumerals('100 Tests', 'Latn', 'Arab'); -> returns '١١٠Tests'173 *174 * @param string $input String to convert175 * @param string $from Script to parse, see {@link Zend_Locale::getScriptList()} for details.176 * @param string $to OPTIONAL Script to convert to177 * @return string Returns the converted input178 * @throws Zend_Locale_Exception179 */180 public static function convertNumerals($input, $from, $to = null)181 {182 if (!self::_getUniCodeSupport()) {183 trigger_error("Sorry, your PCRE extension does not support UTF8 which is needed for the I18N core", E_USER_NOTICE);184 }185 $from = strtolower($from);186 $source = Zend_Locale_Data::getContent('en', 'numberingsystem', $from);187 if (empty($source)) {188 #require_once 'Zend/Locale/Exception.php';189 throw new Zend_Locale_Exception("Unknown script '$from'. Use 'Latn' for digits 0,1,2,3,4,5,6,7,8,9.");190 }191 if ($to !== null) {192 $to = strtolower($to);193 $target = Zend_Locale_Data::getContent('en', 'numberingsystem', $to);194 if (empty($target)) {195 #require_once 'Zend/Locale/Exception.php';196 throw new Zend_Locale_Exception("Unknown script '$to'. Use 'Latn' for digits 0,1,2,3,4,5,6,7,8,9.");197 }198 } else {199 $target = '0123456789';200 }201 for ($x = 0; $x < 10; ++$x) {202 $asource[$x] = "/" . iconv_substr($source, $x, 1, 'UTF-8') . "/u";203 $atarget[$x] = iconv_substr($target, $x, 1, 'UTF-8');204 }205 return preg_replace($asource, $atarget, $input);206 }207 /**208 * Returns the normalized number from a localized one209 * Parsing depends on given locale (grouping and decimal)210 *211 * Examples for input:212 * '2345.4356,1234' = 23455456.1234213 * '+23,3452.123' = 233452.123214 * '12343 ' = 12343215 * '-9456' = -9456216 * '0' = 0217 *218 * @param string $input Input string to parse for numbers219 * @param array $options Options: locale, precision. See {@link setOptions()} for details.220 * @return string Returns the extracted number221 * @throws Zend_Locale_Exception222 */223 public static function getNumber($input, array $options = array())224 {225 $options = self::_checkOptions($options) + self::$_options;226 if (!is_string($input)) {227 return $input;228 }229 if (!self::isNumber($input, $options)) {230 #require_once 'Zend/Locale/Exception.php';231 throw new Zend_Locale_Exception('No localized value in ' . $input . ' found, or the given number does not match the localized format');232 }233 // Get correct signs for this locale234 $symbols = Zend_Locale_Data::getList($options['locale'],'symbols');235 // Change locale input to be default number236 if (($input[0] == $symbols['minus']) && ('-' != $input[0])) {237 $input = '-' . substr($input, 1);238 }239 $input = str_replace($symbols['group'],'', $input);240 if (strpos($input, $symbols['decimal']) !== false) {241 if ($symbols['decimal'] != '.') {242 $input = str_replace($symbols['decimal'], ".", $input);243 }244 $pre = substr($input, strpos($input, '.') + 1);245 if ($options['precision'] === null) {246 $options['precision'] = strlen($pre);247 }248 if (strlen($pre) >= $options['precision']) {249 $input = substr($input, 0, strlen($input) - strlen($pre) + $options['precision']);250 }251 if (($options['precision'] == 0) && ($input[strlen($input) - 1] == '.')) {252 $input = substr($input, 0, -1);253 }254 }255 return $input;256 }257 /**258 * Returns a locale formatted number depending on the given options.259 * The seperation and fraction sign is used from the set locale.260 * ##0.# -> 12345.12345 -> 12345.12345261 * ##0.00 -> 12345.12345 -> 12345.12262 * ##,##0.00 -> 12345.12345 -> 12,345.12263 *264 * @param string $value Localized number string265 * @param array $options Options: number_format, locale, precision. See {@link setOptions()} for details.266 * @return string locale formatted number267 * @throws Zend_Locale_Exception268 */269 public static function toNumber($value, array $options = array())270 {271 // load class within method for speed272 #require_once 'Zend/Locale/Math.php';273 $value = Zend_Locale_Math::floatalize($value);274 $value = Zend_Locale_Math::normalize($value);275 $options = self::_checkOptions($options) + self::$_options;276 $options['locale'] = (string) $options['locale'];277 // Get correct signs for this locale278 $symbols = Zend_Locale_Data::getList($options['locale'], 'symbols');279 $oenc = self::_getEncoding();280 self::_setEncoding('UTF-8');281 282 // Get format283 $format = $options['number_format'];284 if ($format === null) {285 $format = Zend_Locale_Data::getContent($options['locale'], 'decimalnumber');286 $format = self::_seperateFormat($format, $value, $options['precision']);287 if ($options['precision'] !== null) {288 $value = Zend_Locale_Math::normalize(Zend_Locale_Math::round($value, $options['precision']));289 }290 } else {291 // seperate negative format pattern when available292 $format = self::_seperateFormat($format, $value, $options['precision']);293 if (strpos($format, '.')) {294 if (is_numeric($options['precision'])) {295 $value = Zend_Locale_Math::round($value, $options['precision']);296 } else {297 if (substr($format, iconv_strpos($format, '.') + 1, 3) == '###') {298 $options['precision'] = null;299 } else {300 $options['precision'] = iconv_strlen(iconv_substr($format, iconv_strpos($format, '.') + 1,301 iconv_strrpos($format, '0') - iconv_strpos($format, '.')));302 $format = iconv_substr($format, 0, iconv_strpos($format, '.') + 1) . '###'303 . iconv_substr($format, iconv_strrpos($format, '0') + 1);304 }305 }306 } else {307 $value = Zend_Locale_Math::round($value, 0);308 $options['precision'] = 0;309 }310 $value = Zend_Locale_Math::normalize($value);311 }312 if (iconv_strpos($format, '0') === false) {313 self::_setEncoding($oenc);314 #require_once 'Zend/Locale/Exception.php';315 throw new Zend_Locale_Exception('Wrong format... missing 0');316 }317 // get number parts318 $pos = iconv_strpos($value, '.');319 if ($pos !== false) {320 if ($options['precision'] === null) {321 $precstr = iconv_substr($value, $pos + 1);322 } else {323 $precstr = iconv_substr($value, $pos + 1, $options['precision']);324 if (iconv_strlen($precstr) < $options['precision']) {325 $precstr = $precstr . str_pad("0", ($options['precision'] - iconv_strlen($precstr)), "0");326 }327 }328 } else {329 if ($options['precision'] > 0) {330 $precstr = str_pad("0", ($options['precision']), "0");331 }332 }333 if ($options['precision'] === null) {334 if (isset($precstr)) {335 $options['precision'] = iconv_strlen($precstr);336 } else {337 $options['precision'] = 0;338 }339 }340 // get fraction and format lengths341 if (strpos($value, '.') !== false) {342 $number = substr((string) $value, 0, strpos($value, '.'));343 } else {344 $number = $value;345 }346 $prec = call_user_func(Zend_Locale_Math::$sub, $value, $number, $options['precision']);347 $prec = Zend_Locale_Math::floatalize($prec);348 $prec = Zend_Locale_Math::normalize($prec);349 if (iconv_strpos($prec, '-') !== false) {350 $prec = iconv_substr($prec, 1);351 }352 if (($prec == 0) and ($options['precision'] > 0)) {353 $prec = "0.0";354 }355 if (($options['precision'] + 2) > iconv_strlen($prec)) {356 $prec = str_pad((string) $prec, $options['precision'] + 2, "0", STR_PAD_RIGHT);357 }358 if (iconv_strpos($number, '-') !== false) {359 $number = iconv_substr($number, 1);360 }361 $group = iconv_strrpos($format, ',');362 $group2 = iconv_strpos ($format, ',');363 $point = iconv_strpos ($format, '0');364 // Add fraction365 $rest = "";366 if (iconv_strpos($format, '.')) {367 $rest = iconv_substr($format, iconv_strpos($format, '.') + 1);368 $length = iconv_strlen($rest);369 for($x = 0; $x < $length; ++$x) {370 if (($rest[0] == '0') || ($rest[0] == '#')) {371 $rest = iconv_substr($rest, 1);372 }373 }374 $format = iconv_substr($format, 0, iconv_strlen($format) - iconv_strlen($rest));375 }376 if ($options['precision'] == '0') {377 if (iconv_strrpos($format, '-') != 0) {378 $format = iconv_substr($format, 0, $point)379 . iconv_substr($format, iconv_strrpos($format, '#') + 2);380 } else {381 $format = iconv_substr($format, 0, $point);382 }383 } else {384 $format = iconv_substr($format, 0, $point) . $symbols['decimal']385 . iconv_substr($prec, 2);386 }387 $format .= $rest;388 // Add seperation389 if ($group == 0) {390 // no seperation391 $format = $number . iconv_substr($format, $point);392 } else if ($group == $group2) {393 // only 1 seperation394 $seperation = ($point - $group);395 for ($x = iconv_strlen($number); $x > $seperation; $x -= $seperation) {396 if (iconv_substr($number, 0, $x - $seperation) !== "") {397 $number = iconv_substr($number, 0, $x - $seperation) . $symbols['group']398 . iconv_substr($number, $x - $seperation);399 }400 }401 $format = iconv_substr($format, 0, iconv_strpos($format, '#')) . $number . iconv_substr($format, $point);402 } else {403 // 2 seperations404 if (iconv_strlen($number) > ($point - $group)) {405 $seperation = ($point - $group);406 $number = iconv_substr($number, 0, iconv_strlen($number) - $seperation) . $symbols['group']407 . iconv_substr($number, iconv_strlen($number) - $seperation);408 if ((iconv_strlen($number) - 1) > ($point - $group + 1)) {409 $seperation2 = ($group - $group2 - 1);410 for ($x = iconv_strlen($number) - $seperation2 - 2; $x > $seperation2; $x -= $seperation2) {411 $number = iconv_substr($number, 0, $x - $seperation2) . $symbols['group']412 . iconv_substr($number, $x - $seperation2);413 }414 }415 }416 $format = iconv_substr($format, 0, iconv_strpos($format, '#')) . $number . iconv_substr($format, $point);417 }418 // set negative sign419 if (call_user_func(Zend_Locale_Math::$comp, $value, 0, $options['precision']) < 0) {420 if (iconv_strpos($format, '-') === false) {421 $format = $symbols['minus'] . $format;422 } else {423 $format = str_replace('-', $symbols['minus'], $format);424 }425 }426 self::_setEncoding($oenc);427 return (string) $format;428 }429 /**430 * @param string $format431 * @param string $value432 * @param int $precision433 * @return string434 */435 private static function _seperateFormat($format, $value, $precision)436 {437 if (iconv_strpos($format, ';') !== false) {438 if (call_user_func(Zend_Locale_Math::$comp, $value, 0, $precision) < 0) {439 $tmpformat = iconv_substr($format, iconv_strpos($format, ';') + 1);440 if ($tmpformat[0] == '(') {441 $format = iconv_substr($format, 0, iconv_strpos($format, ';'));442 } else {443 $format = $tmpformat;444 }445 } else {446 $format = iconv_substr($format, 0, iconv_strpos($format, ';'));447 }448 }449 return $format;450 }451 /**452 * Checks if the input contains a normalized or localized number453 *454 * @param string $input Localized number string455 * @param array $options Options: locale. See {@link setOptions()} for details.456 * @return boolean Returns true if a number was found457 */458 public static function isNumber($input, array $options = array())459 {460 if (!self::_getUniCodeSupport()) {461 trigger_error("Sorry, your PCRE extension does not support UTF8 which is needed for the I18N core", E_USER_NOTICE);462 }463 $options = self::_checkOptions($options) + self::$_options;464 // Get correct signs for this locale465 $symbols = Zend_Locale_Data::getList($options['locale'],'symbols');466 $regexs = Zend_Locale_Format::_getRegexForType('decimalnumber', $options);467 $regexs = array_merge($regexs, Zend_Locale_Format::_getRegexForType('scientificnumber', $options));468 if (!empty($input) && ($input[0] == $symbols['decimal'])) {469 $input = 0 . $input;470 }471 foreach ($regexs as $regex) {472 preg_match($regex, $input, $found);473 if (isset($found[0])) {474 return true;475 }476 }477 return false;478 }479 /**480 * Internal method to convert cldr number syntax into regex481 *482 * @param string $type483 * @param array $options Options: locale. See {@link setOptions()} for details.484 * @return string485 * @throws Zend_Locale_Exception486 */487 private static function _getRegexForType($type, $options)488 {489 $decimal = Zend_Locale_Data::getContent($options['locale'], $type);490 $decimal = preg_replace('/[^#0,;\.\-Ee]/u', '',$decimal);491 $patterns = explode(';', $decimal);492 if (count($patterns) == 1) {493 $patterns[1] = '-' . $patterns[0];494 }495 $symbols = Zend_Locale_Data::getList($options['locale'],'symbols');496 foreach($patterns as $pkey => $pattern) {497 $regex[$pkey] = '/^';498 $rest = 0;499 $end = null;500 if (strpos($pattern, '.') !== false) {501 $end = substr($pattern, strpos($pattern, '.') + 1);502 $pattern = substr($pattern, 0, -strlen($end) - 1);503 }504 if (strpos($pattern, ',') !== false) {505 $parts = explode(',', $pattern);506 $count = count($parts);507 foreach($parts as $key => $part) {508 switch ($part) {509 case '#':510 case '-#':511 if ($part[0] == '-') {512 $regex[$pkey] .= '[' . $symbols['minus'] . '-]{0,1}';513 } else {514 $regex[$pkey] .= '[' . $symbols['plus'] . '+]{0,1}';515 }516 if (($parts[$key + 1]) == '##0') {517 $regex[$pkey] .= '[0-9]{1,3}';518 } else if (($parts[$key + 1]) == '##') {519 $regex[$pkey] .= '[0-9]{1,2}';520 } else {521 throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 1):"' . $pattern . '"');522 }523 break;524 case '##':525 if ($parts[$key + 1] == '##0') {526 $regex[$pkey] .= '(\\' . $symbols['group'] . '{0,1}[0-9]{2})*';527 } else {528 throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 2):"' . $pattern . '"');529 }530 break;531 case '##0':532 if ($parts[$key - 1] == '##') {533 $regex[$pkey] .= '[0-9]';534 } else if (($parts[$key - 1] == '#') || ($parts[$key - 1] == '-#')) {535 $regex[$pkey] .= '(\\' . $symbols['group'] . '{0,1}[0-9]{3})*';536 } else {537 throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 3):"' . $pattern . '"');538 }539 break;540 case '#0':541 if ($key == 0) {542 $regex[$pkey] .= '[0-9]*';543 } else {544 throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 4):"' . $pattern . '"');545 }546 break;547 }548 }549 }550 if (strpos($pattern, 'E') !== false) {551 if (($pattern == '#E0') || ($pattern == '#E00')) {552 $regex[$pkey] .= '[' . $symbols['plus']. '+]{0,1}[0-9]{1,}(\\' . $symbols['decimal'] . '[0-9]{1,})*[eE][' . $symbols['plus']. '+]{0,1}[0-9]{1,}';553 } else if (($pattern == '-#E0') || ($pattern == '-#E00')) {554 $regex[$pkey] .= '[' . $symbols['minus']. '-]{0,1}[0-9]{1,}(\\' . $symbols['decimal'] . '[0-9]{1,})*[eE][' . $symbols['minus']. '-]{0,1}[0-9]{1,}';555 } else {556 throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 5):"' . $pattern . '"');557 }558 }559 if (!empty($end)) {560 if ($end == '###') {561 $regex[$pkey] .= '(\\' . $symbols['decimal'] . '{1}[0-9]{1,}){0,1}';562 } else if ($end == '###-') {563 $regex[$pkey] .= '(\\' . $symbols['decimal'] . '{1}[0-9]{1,}){0,1}[' . $symbols['minus']. '-]';564 } else {565 throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 6):"' . $pattern . '"');566 }567 }568 $regex[$pkey] .= '$/u';569 }570 return $regex;571 }572 /**573 * Alias for getNumber574 *575 * @param string $input Number to localize576 * @param array $options Options: locale, precision. See {@link setOptions()} for details.577 * @return float578 */579 public static function getFloat($input, array $options = array())580 {581 return floatval(self::getNumber($input, $options));582 }583 /**584 * Returns a locale formatted integer number585 * Alias for toNumber()586 *587 * @param string $value Number to normalize588 * @param array $options Options: locale, precision. See {@link setOptions()} for details.589 * @return string Locale formatted number590 */591 public static function toFloat($value, array $options = array())592 {593 $options['number_format'] = Zend_Locale_Format::STANDARD;594 return self::toNumber($value, $options);595 }596 /**597 * Returns if a float was found598 * Alias for isNumber()599 *600 * @param string $value Localized number string601 * @param array $options Options: locale. See {@link setOptions()} for details.602 * @return boolean Returns true if a number was found603 */604 public static function isFloat($value, array $options = array())605 {606 return self::isNumber($value, $options);607 }608 /**609 * Returns the first found integer from an string610 * Parsing depends on given locale (grouping and decimal)611 *612 * Examples for input:613 * ' 2345.4356,1234' = 23455456614 * '+23,3452.123' = 233452615 * ' 12343 ' = 12343616 * '-9456km' = -9456617 * '0' = 0618 * '(-){0,1}(\d+(\.){0,1})*(\,){0,1})\d+'619 *620 * @param string $input Input string to parse for numbers621 * @param array $options Options: locale. See {@link setOptions()} for details.622 * @return integer Returns the extracted number623 */624 public static function getInteger($input, array $options = array())625 {626 $options['precision'] = 0;627 return intval(self::getFloat($input, $options));628 }629 /**630 * Returns a localized number631 *632 * @param string $value Number to normalize633 * @param array $options Options: locale. See {@link setOptions()} for details.634 * @return string Locale formatted number635 */636 public static function toInteger($value, array $options = array())637 {638 $options['precision'] = 0;639 $options['number_format'] = Zend_Locale_Format::STANDARD;640 return self::toNumber($value, $options);641 }642 /**643 * Returns if a integer was found644 *645 * @param string $value Localized number string646 * @param array $options Options: locale. See {@link setOptions()} for details.647 * @return boolean Returns true if a integer was found648 */649 public static function isInteger($value, array $options = array())650 {651 if (!self::isNumber($value, $options)) {652 return false;653 }654 if (self::getInteger($value, $options) == self::getFloat($value, $options)) {655 return true;656 }657 return false;658 }659 /**660 * Converts a format string from PHP's date format to ISO format661 * Remember that Zend Date always returns localized string, so a month name which returns the english662 * month in php's date() will return the translated month name with this function... use 'en' as locale663 * if you are in need of the original english names664 *665 * The conversion has the following restrictions:666 * 'a', 'A' - Meridiem is not explicit upper/lowercase, you have to upper/lowercase the translated value yourself667 *668 * @param string $format Format string in PHP's date format669 * @return string Format string in ISO format670 */671 public static function convertPhpToIsoFormat($format)672 {673 if ($format === null) {674 return null;675 }676 $convert = array(677 'd' => 'dd' , 'D' => 'EE' , 'j' => 'd' , 'l' => 'EEEE',678 'N' => 'eee' , 'S' => 'SS' , 'w' => 'e' , 'z' => 'D' ,679 'W' => 'ww' , 'F' => 'MMMM', 'm' => 'MM' , 'M' => 'MMM' ,680 'n' => 'M' , 't' => 'ddd' , 'L' => 'l' , 'o' => 'YYYY',681 'Y' => 'yyyy', 'y' => 'yy' , 'a' => 'a' , 'A' => 'a' ,682 'B' => 'B' , 'g' => 'h' , 'G' => 'H' , 'h' => 'hh' ,683 'H' => 'HH' , 'i' => 'mm' , 's' => 'ss' , 'e' => 'zzzz',684 'I' => 'I' , 'O' => 'Z' , 'P' => 'ZZZZ', 'T' => 'z' ,685 'Z' => 'X' , 'c' => 'yyyy-MM-ddTHH:mm:ssZZZZ', 'r' => 'r',686 'U' => 'U',687 );688 $escaped = false;689 $inEscapedString = false;690 $converted = array();691 foreach (str_split($format) as $char) {692 if (!$escaped && $char == '\\') {693 // Next char will be escaped: let's remember it694 $escaped = true;695 } elseif ($escaped) {696 if (!$inEscapedString) {697 // First escaped string: start the quoted chunk698 $converted[] = "'";699 $inEscapedString = true;700 }701 // Since the previous char was a \ and we are in the quoted702 // chunk, let's simply add $char as it is703 $converted[] = $char;704 $escaped = false;705 } elseif ($char == "'") {706 // Single quotes need to be escaped like this707 $converted[] = "''";708 } else {709 if ($inEscapedString) {710 // Close the single-quoted chunk711 $converted[] = "'";712 $inEscapedString = false;713 }714 // Convert the unescaped char if needed715 if (isset($convert[$char])) {716 $converted[] = $convert[$char];717 } else {718 $converted[] = $char;719 }720 }721 }722 return implode($converted);723 }724 /**725 * Parse date and split in named array fields726 *727 * @param string $date Date string to parse728 * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.729 * @return array Possible array members: day, month, year, hour, minute, second, fixed, format730 * @throws Zend_Locale_Exception731 */732 private static function _parseDate($date, $options)733 {734 if (!self::_getUniCodeSupport()) {735 trigger_error("Sorry, your PCRE extension does not support UTF8 which is needed for the I18N core", E_USER_NOTICE);736 }737 $options = self::_checkOptions($options) + self::$_options;738 $test = array('h', 'H', 'm', 's', 'y', 'Y', 'M', 'd', 'D', 'E', 'S', 'l', 'B', 'I',739 'X', 'r', 'U', 'G', 'w', 'e', 'a', 'A', 'Z', 'z', 'v');740 $format = $options['date_format'];741 $number = $date; // working copy742 $result['date_format'] = $format; // save the format used to normalize $number (convenience)743 $result['locale'] = $options['locale']; // save the locale used to normalize $number (convenience)744 $oenc = self::_getEncoding();745 self::_setEncoding('UTF-8');746 $day = iconv_strpos($format, 'd');747 $month = iconv_strpos($format, 'M');748 $year = iconv_strpos($format, 'y');749 $hour = iconv_strpos($format, 'H');750 $min = iconv_strpos($format, 'm');751 $sec = iconv_strpos($format, 's');752 $am = null;753 if ($hour === false) {754 $hour = iconv_strpos($format, 'h');755 }756 if ($year === false) {757 $year = iconv_strpos($format, 'Y');758 }759 if ($day === false) {760 $day = iconv_strpos($format, 'E');761 if ($day === false) {762 $day = iconv_strpos($format, 'D');763 }764 }765 if ($day !== false) {766 $parse[$day] = 'd';767 if (!empty($options['locale']) && ($options['locale'] !== 'root') &&768 (!is_object($options['locale']) || ((string) $options['locale'] !== 'root'))) {769 // erase day string770 $daylist = Zend_Locale_Data::getList($options['locale'], 'day');771 foreach($daylist as $key => $name) {772 if (iconv_strpos($number, $name) !== false) {773 $number = str_replace($name, "EEEE", $number);774 break;775 }776 }777 }778 }779 $position = false;780 if ($month !== false) {781 $parse[$month] = 'M';782 if (!empty($options['locale']) && ($options['locale'] !== 'root') &&783 (!is_object($options['locale']) || ((string) $options['locale'] !== 'root'))) {784 // prepare to convert month name to their numeric equivalents, if requested,785 // and we have a $options['locale']786 $position = self::_replaceMonth($number, Zend_Locale_Data::getList($options['locale'],787 'month'));788 if ($position === false) {789 $position = self::_replaceMonth($number, Zend_Locale_Data::getList($options['locale'],790 'month', array('gregorian', 'format', 'abbreviated')));791 }792 }793 }794 if ($year !== false) {795 $parse[$year] = 'y';796 }797 if ($hour !== false) {798 $parse[$hour] = 'H';799 }800 if ($min !== false) {801 $parse[$min] = 'm';802 }803 if ($sec !== false) {804 $parse[$sec] = 's';805 }806 if (empty($parse)) {807 self::_setEncoding($oenc);808 #require_once 'Zend/Locale/Exception.php';809 throw new Zend_Locale_Exception("Unknown date format, neither date nor time in '" . $format . "' found");810 }811 ksort($parse);812 // get daytime813 if (iconv_strpos($format, 'a') !== false) {814 if (iconv_strpos(strtoupper($number), strtoupper(Zend_Locale_Data::getContent($options['locale'], 'am'))) !== false) {815 $am = true;816 } else if (iconv_strpos(strtoupper($number), strtoupper(Zend_Locale_Data::getContent($options['locale'], 'pm'))) !== false) {817 $am = false;818 }819 }820 // split number parts821 $split = false;822 preg_match_all('/\d+/u', $number, $splitted);823 if (count($splitted[0]) == 0) {824 self::_setEncoding($oenc);825 #require_once 'Zend/Locale/Exception.php';826 throw new Zend_Locale_Exception("No date part in '$date' found.");827 }828 if (count($splitted[0]) == 1) {829 $split = 0;830 }831 $cnt = 0;832 foreach($parse as $key => $value) {833 switch($value) {834 case 'd':835 if ($split === false) {836 if (count($splitted[0]) > $cnt) {837 $result['day'] = $splitted[0][$cnt];838 }839 } else {840 $result['day'] = iconv_substr($splitted[0][0], $split, 2);841 $split += 2;842 }843 ++$cnt;844 break;845 case 'M':846 if ($split === false) {847 if (count($splitted[0]) > $cnt) {848 $result['month'] = $splitted[0][$cnt];849 }850 } else {851 $result['month'] = iconv_substr($splitted[0][0], $split, 2);852 $split += 2;853 }854 ++$cnt;855 break;856 case 'y':857 $length = 2;858 if ((iconv_substr($format, $year, 4) == 'yyyy')859 || (iconv_substr($format, $year, 4) == 'YYYY')) {860 $length = 4;861 }862 if ($split === false) {863 if (count($splitted[0]) > $cnt) {864 $result['year'] = $splitted[0][$cnt];865 }866 } else {867 $result['year'] = iconv_substr($splitted[0][0], $split, $length);868 $split += $length;869 }870 ++$cnt;871 break;872 case 'H':873 if ($split === false) {874 if (count($splitted[0]) > $cnt) {875 $result['hour'] = $splitted[0][$cnt];876 }877 } else {878 $result['hour'] = iconv_substr($splitted[0][0], $split, 2);879 $split += 2;880 }881 ++$cnt;882 break;883 case 'm':884 if ($split === false) {885 if (count($splitted[0]) > $cnt) {886 $result['minute'] = $splitted[0][$cnt];887 }888 } else {889 $result['minute'] = iconv_substr($splitted[0][0], $split, 2);890 $split += 2;891 }892 ++$cnt;893 break;894 case 's':895 if ($split === false) {896 if (count($splitted[0]) > $cnt) {897 $result['second'] = $splitted[0][$cnt];898 }899 } else {900 $result['second'] = iconv_substr($splitted[0][0], $split, 2);901 $split += 2;902 }903 ++$cnt;904 break;905 }906 }907 // AM/PM correction908 if ($hour !== false) {909 if (($am === true) and ($result['hour'] == 12)){910 $result['hour'] = 0;911 } else if (($am === false) and ($result['hour'] != 12)) {912 $result['hour'] += 12;913 }914 }915 if ($options['fix_date'] === true) {916 $result['fixed'] = 0; // nothing has been "fixed" by swapping date parts around (yet)917 }918 if ($day !== false) {919 // fix false month920 if (isset($result['day']) and isset($result['month'])) {921 if (($position !== false) and ((iconv_strpos($date, $result['day']) === false) or922 (isset($result['year']) and (iconv_strpos($date, $result['year']) === false)))) {923 if ($options['fix_date'] !== true) {924 self::_setEncoding($oenc);925 #require_once 'Zend/Locale/Exception.php';926 throw new Zend_Locale_Exception("Unable to parse date '$date' using '" . $format927 . "' (false month, $position, $month)");928 }929 $temp = $result['day'];930 $result['day'] = $result['month'];931 $result['month'] = $temp;932 $result['fixed'] = 1;933 }934 }935 // fix switched values d <> y936 if (isset($result['day']) and isset($result['year'])) {937 if ($result['day'] > 31) {938 if ($options['fix_date'] !== true) {939 self::_setEncoding($oenc);940 #require_once 'Zend/Locale/Exception.php';941 throw new Zend_Locale_Exception("Unable to parse date '$date' using '"942 . $format . "' (d <> y)");943 }944 $temp = $result['year'];945 $result['year'] = $result['day'];946 $result['day'] = $temp;947 $result['fixed'] = 2;948 }949 }950 // fix switched values M <> y951 if (isset($result['month']) and isset($result['year'])) {952 if ($result['month'] > 31) {953 if ($options['fix_date'] !== true) {954 self::_setEncoding($oenc);955 #require_once 'Zend/Locale/Exception.php';956 throw new Zend_Locale_Exception("Unable to parse date '$date' using '"957 . $format . "' (M <> y)");958 }959 $temp = $result['year'];960 $result['year'] = $result['month'];961 $result['month'] = $temp;962 $result['fixed'] = 3;963 }964 }965 // fix switched values M <> d966 if (isset($result['month']) and isset($result['day'])) {967 if ($result['month'] > 12) {968 if ($options['fix_date'] !== true || $result['month'] > 31) {969 self::_setEncoding($oenc);970 #require_once 'Zend/Locale/Exception.php';971 throw new Zend_Locale_Exception("Unable to parse date '$date' using '"972 . $format . "' (M <> d)");973 }974 $temp = $result['day'];975 $result['day'] = $result['month'];976 $result['month'] = $temp;977 $result['fixed'] = 4;978 }979 }980 }981 if (isset($result['year'])) {982 if (((iconv_strlen($result['year']) == 2) && ($result['year'] < 10)) ||983 (((iconv_strpos($format, 'yy') !== false) && (iconv_strpos($format, 'yyyy') === false)) ||984 ((iconv_strpos($format, 'YY') !== false) && (iconv_strpos($format, 'YYYY') === false)))) {985 if (($result['year'] >= 0) && ($result['year'] < 100)) {986 if ($result['year'] < 70) {987 $result['year'] = (int) $result['year'] + 100;988 }989 $result['year'] = (int) $result['year'] + 1900;990 }991 }992 }993 self::_setEncoding($oenc);994 return $result;995 }996 /**997 * Search $number for a month name found in $monthlist, and replace if found.998 *999 * @param string $number Date string (modified)1000 * @param array $monthlist List of month names1001 *1002 * @return int|false Position of replaced string (false if nothing replaced)1003 */1004 protected static function _replaceMonth(&$number, $monthlist)1005 {1006 // If $locale was invalid, $monthlist will default to a "root" identity1007 // mapping for each month number from 1 to 12.1008 // If no $locale was given, or $locale was invalid, do not use this identity mapping to normalize.1009 // Otherwise, translate locale aware month names in $number to their numeric equivalents.1010 $position = false;1011 if ($monthlist && $monthlist[1] != 1) {1012 foreach($monthlist as $key => $name) {1013 if (($position = iconv_strpos($number, $name, 0, 'UTF-8')) !== false) {1014 $number = str_ireplace($name, $key, $number);1015 return $position;1016 }1017 }1018 }1019 return false;1020 }1021 /**1022 * Returns the default date format for $locale.1023 *1024 * @param string|Zend_Locale $locale OPTIONAL Locale of $number, possibly in string form (e.g. 'de_AT')1025 * @return string format1026 * @throws Zend_Locale_Exception throws an exception when locale data is broken1027 */1028 public static function getDateFormat($locale = null)1029 {1030 $format = Zend_Locale_Data::getContent($locale, 'date');1031 if (empty($format)) {1032 #require_once 'Zend/Locale/Exception.php';1033 throw new Zend_Locale_Exception("failed to receive data from locale $locale");1034 }1035 return $format;1036 }1037 /**1038 * Returns an array with the normalized date from an locale date1039 * a input of 10.01.2006 without a $locale would return:1040 * array ('day' => 10, 'month' => 1, 'year' => 2006)1041 * The 'locale' option is only used to convert human readable day1042 * and month names to their numeric equivalents.1043 * The 'format' option allows specification of self-defined date formats,1044 * when not using the default format for the 'locale'.1045 *1046 * @param string $date Date string1047 * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.1048 * @return array Possible array members: day, month, year, hour, minute, second, fixed, format1049 */1050 public static function getDate($date, array $options = array())1051 {1052 $options = self::_checkOptions($options) + self::$_options;1053 if (empty($options['date_format'])) {1054 $options['format_type'] = 'iso';1055 $options['date_format'] = self::getDateFormat($options['locale']);1056 }1057 return self::_parseDate($date, $options);1058 }1059 /**1060 * Returns if the given datestring contains all date parts from the given format.1061 * If no format is given, the default date format from the locale is used1062 * If you want to check if the date is a proper date you should use Zend_Date::isDate()1063 *1064 * @param string $date Date string1065 * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.1066 * @return boolean1067 */1068 public static function checkDateFormat($date, array $options = array())1069 {1070 try {1071 $date = self::getDate($date, $options);1072 } catch (Exception $e) {1073 return false;1074 }1075 if (empty($options['date_format'])) {1076 $options['format_type'] = 'iso';1077 $options['date_format'] = self::getDateFormat(isset($options['locale']) ? $options['locale'] : null);1078 }1079 $options = self::_checkOptions($options) + self::$_options;1080 // day expected but not parsed1081 if ((iconv_strpos($options['date_format'], 'd', 0, 'UTF-8') !== false) and (!isset($date['day']) or ($date['day'] === ""))) {1082 return false;1083 }1084 // month expected but not parsed1085 if ((iconv_strpos($options['date_format'], 'M', 0, 'UTF-8') !== false) and (!isset($date['month']) or ($date['month'] === ""))) {1086 return false;1087 }1088 // year expected but not parsed1089 if (((iconv_strpos($options['date_format'], 'Y', 0, 'UTF-8') !== false) or1090 (iconv_strpos($options['date_format'], 'y', 0, 'UTF-8') !== false)) and (!isset($date['year']) or ($date['year'] === ""))) {1091 return false;1092 }1093 // second expected but not parsed1094 if ((iconv_strpos($options['date_format'], 's', 0, 'UTF-8') !== false) and (!isset($date['second']) or ($date['second'] === ""))) {1095 return false;1096 }1097 // minute expected but not parsed1098 if ((iconv_strpos($options['date_format'], 'm', 0, 'UTF-8') !== false) and (!isset($date['minute']) or ($date['minute'] === ""))) {1099 return false;1100 }1101 // hour expected but not parsed1102 if (((iconv_strpos($options['date_format'], 'H', 0, 'UTF-8') !== false) or1103 (iconv_strpos($options['date_format'], 'h', 0, 'UTF-8') !== false)) and (!isset($date['hour']) or ($date['hour'] === ""))) {1104 return false;1105 }1106 return true;1107 }1108 /**1109 * Returns the default time format for $locale.1110 *1111 * @param string|Zend_Locale $locale OPTIONAL Locale of $number, possibly in string form (e.g. 'de_AT')1112 * @return string format1113 * @throws Zend_Locale_Exception1114 */1115 public static function getTimeFormat($locale = null)1116 {1117 $format = Zend_Locale_Data::getContent($locale, 'time');1118 if (empty($format)) {1119 #require_once 'Zend/Locale/Exception.php';1120 throw new Zend_Locale_Exception("failed to receive data from locale $locale");1121 }1122 return $format;1123 }1124 /**1125 * Returns an array with 'hour', 'minute', and 'second' elements extracted from $time1126 * according to the order described in $format. For a format of 'H:i:s', and1127 * an input of 11:20:55, getTime() would return:1128 * array ('hour' => 11, 'minute' => 20, 'second' => 55)1129 * The optional $locale parameter may be used to help extract times from strings1130 * containing both a time and a day or month name.1131 *1132 * @param string $time Time string1133 * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.1134 * @return array Possible array members: day, month, year, hour, minute, second, fixed, format1135 */1136 public static function getTime($time, array $options = array())1137 {1138 $options = self::_checkOptions($options) + self::$_options;1139 if (empty($options['date_format'])) {1140 $options['format_type'] = 'iso';1141 $options['date_format'] = self::getTimeFormat($options['locale']);1142 }1143 return self::_parseDate($time, $options);1144 }1145 /**1146 * Returns the default datetime format for $locale.1147 *1148 * @param string|Zend_Locale $locale OPTIONAL Locale of $number, possibly in string form (e.g. 'de_AT')1149 * @return string format1150 * @throws Zend_Locale_Exception1151 */1152 public static function getDateTimeFormat($locale = null)1153 {1154 $format = Zend_Locale_Data::getContent($locale, 'datetime');1155 if (empty($format)) {1156 #require_once 'Zend/Locale/Exception.php';1157 throw new Zend_Locale_Exception("failed to receive data from locale $locale");1158 }1159 return $format;1160 }1161 /**1162 * Returns an array with 'year', 'month', 'day', 'hour', 'minute', and 'second' elements1163 * extracted from $datetime according to the order described in $format. For a format of 'd.M.y H:i:s',1164 * and an input of 10.05.1985 11:20:55, getDateTime() would return:1165 * array ('year' => 1985, 'month' => 5, 'day' => 10, 'hour' => 11, 'minute' => 20, 'second' => 55)1166 * The optional $locale parameter may be used to help extract times from strings1167 * containing both a time and a day or month name.1168 *1169 * @param string $datetime DateTime string1170 * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.1171 * @return array Possible array members: day, month, year, hour, minute, second, fixed, format1172 */1173 public static function getDateTime($datetime, array $options = array())1174 {1175 $options = self::_checkOptions($options) + self::$_options;1176 if (empty($options['date_format'])) {1177 $options['format_type'] = 'iso';1178 $options['date_format'] = self::getDateTimeFormat($options['locale']);1179 }1180 return self::_parseDate($datetime, $options);1181 }1182 /**1183 * Internal method to detect of Unicode supports UTF81184 * which should be enabled within vanilla php installations1185 *1186 * @return boolean1187 */1188 protected static function _getUniCodeSupport()1189 {1190 return (@preg_match('/\pL/u', 'a')) ? true : false;1191 }1192 /**...
Zend_Locale_Format.php
Source:Zend_Locale_Format.php
...32 */33class Zend_Locale_Format34{35 const STANDARD = 'auto';36 private static $_options = array('date_format' => null,37 'number_format' => null,38 'format_type' => 'iso',39 'fix_date' => false,40 'locale' => null,41 'cache' => null,42 'disableCache' => null,43 'precision' => null);44 /**45 * Sets class wide options, if no option was given, the actual set options will be returned46 * The 'precision' option of a value is used to truncate or stretch extra digits. -1 means not to touch the extra digits.47 * The 'locale' option helps when parsing numbers and dates using separators and month names.48 * The date format 'format_type' option selects between CLDR/ISO date format specifier tokens and PHP's date() tokens.49 * The 'fix_date' option enables or disables heuristics that attempt to correct invalid dates.50 * The 'number_format' option can be used to specify a default number format string51 * The 'date_format' option can be used to specify a default date format string, but beware of using getDate(),52 * checkDateFormat() and getTime() after using setOptions() with a 'format'. To use these four methods53 * with the default date format for a locale, use array('date_format' => null, 'locale' => $locale) for their options.54 *55 * @param array $options Array of options, keyed by option name: format_type = 'iso' | 'php', fix_date = true | false,56 * locale = Zend_Locale | locale string, precision = whole number between -1 and 3057 * @throws Zend_Locale_Exception58 * @return array if no option was given59 */60 public static function setOptions(array $options = array())61 {62 self::$_options = self::_checkOptions($options) + self::$_options;63 return self::$_options;64 }65 /**66 * Internal function for checking the options array of proper input values67 * See {@link setOptions()} for details.68 *69 * @param array $options Array of options, keyed by option name: format_type = 'iso' | 'php', fix_date = true | false,70 * locale = Zend_Locale | locale string, precision = whole number between -1 and 3071 * @throws Zend_Locale_Exception72 * @return array if no option was given73 */74 private static function _checkOptions(array $options = array())75 {76 if (count($options) == 0) {77 return self::$_options;78 }79 foreach ($options as $name => $value) {80 $name = strtolower($name);81 if ($name !== 'locale') {82 if (gettype($value) === 'string') {83 $value = strtolower($value);84 }85 }86 switch($name) {87 case 'number_format' :88 if ($value == Zend_Locale_Format::STANDARD) {89 $locale = self::$_options['locale'];90 if (isset($options['locale'])) {91 $locale = $options['locale'];92 }93 $options['number_format'] = Zend_Locale_Data::getContent($locale, 'decimalnumber');94 } else if ((gettype($value) !== 'string') and ($value !== NULL)) {95 #require_once 'Zend/Locale/Exception.php';96 $stringValue = (string)(is_array($value) ? implode(' ', $value) : $value);97 throw new Zend_Locale_Exception("Unknown number format type '" . gettype($value) . "'. "98 . "Format '$stringValue' must be a valid number format string.");99 }100 break;101 case 'date_format' :102 if ($value == Zend_Locale_Format::STANDARD) {103 $locale = self::$_options['locale'];104 if (isset($options['locale'])) {105 $locale = $options['locale'];106 }107 $options['date_format'] = Zend_Locale_Format::getDateFormat($locale);108 } else if ((gettype($value) !== 'string') and ($value !== NULL)) {109 #require_once 'Zend/Locale/Exception.php';110 $stringValue = (string)(is_array($value) ? implode(' ', $value) : $value);111 throw new Zend_Locale_Exception("Unknown dateformat type '" . gettype($value) . "'. "112 . "Format '$stringValue' must be a valid ISO or PHP date format string.");113 } else {114 if (((isset($options['format_type']) === true) and ($options['format_type'] == 'php')) or115 ((isset($options['format_type']) === false) and (self::$_options['format_type'] == 'php'))) {116 $options['date_format'] = Zend_Locale_Format::convertPhpToIsoFormat($value);117 }118 }119 break;120 case 'format_type' :121 if (($value != 'php') && ($value != 'iso')) {122 #require_once 'Zend/Locale/Exception.php';123 throw new Zend_Locale_Exception("Unknown date format type '$value'. Only 'iso' and 'php'"124 . " are supported.");125 }126 break;127 case 'fix_date' :128 if (($value !== true) && ($value !== false)) {129 #require_once 'Zend/Locale/Exception.php';130 throw new Zend_Locale_Exception("Enabling correction of dates must be either true or false"131 . "(fix_date='$value').");132 }133 break;134 case 'locale' :135 $options['locale'] = Zend_Locale::findLocale($value);136 break;137 case 'cache' :138 if ($value instanceof Zend_Cache_Core) {139 Zend_Locale_Data::setCache($value);140 }141 break;142 case 'disablecache' :143 if (null !== $value) {144 Zend_Locale_Data::disableCache($value);145 }146 break;147 case 'precision' :148 if ($value === NULL) {149 $value = -1;150 }151 if (($value < -1) || ($value > 30)) {152 #require_once 'Zend/Locale/Exception.php';153 throw new Zend_Locale_Exception("'$value' precision is not a whole number less than 30.");154 }155 break;156 default:157 #require_once 'Zend/Locale/Exception.php';158 throw new Zend_Locale_Exception("Unknown option: '$name' = '$value'");159 break;160 }161 }162 return $options;163 }164 /**165 * Changes the numbers/digits within a given string from one script to another166 * 'Decimal' representated the stardard numbers 0-9, if a script does not exist167 * an exception will be thrown.168 *169 * Examples for conversion from Arabic to Latin numerals:170 * convertNumerals('١١٠Tests', 'Arab'); -> returns '100 Tests'171 * Example for conversion from Latin to Arabic numerals:172 * convertNumerals('100 Tests', 'Latn', 'Arab'); -> returns '١١٠Tests'173 *174 * @param string $input String to convert175 * @param string $from Script to parse, see {@link Zend_Locale::getScriptList()} for details.176 * @param string $to OPTIONAL Script to convert to177 * @return string Returns the converted input178 * @throws Zend_Locale_Exception179 */180 public static function convertNumerals($input, $from, $to = null)181 {182 if (!self::_getUniCodeSupport()) {183 trigger_error("Sorry, your PCRE extension does not support UTF8 which is needed for the I18N core", E_USER_NOTICE);184 }185 $from = strtolower($from);186 $source = Zend_Locale_Data::getContent('en', 'numberingsystem', $from);187 if (empty($source)) {188 #require_once 'Zend/Locale/Exception.php';189 throw new Zend_Locale_Exception("Unknown script '$from'. Use 'Latn' for digits 0,1,2,3,4,5,6,7,8,9.");190 }191 if ($to !== null) {192 $to = strtolower($to);193 $target = Zend_Locale_Data::getContent('en', 'numberingsystem', $to);194 if (empty($target)) {195 #require_once 'Zend/Locale/Exception.php';196 throw new Zend_Locale_Exception("Unknown script '$to'. Use 'Latn' for digits 0,1,2,3,4,5,6,7,8,9.");197 }198 } else {199 $target = '0123456789';200 }201 for ($x = 0; $x < 10; ++$x) {202 $asource[$x] = "/" . iconv_substr($source, $x, 1, 'UTF-8') . "/u";203 $atarget[$x] = iconv_substr($target, $x, 1, 'UTF-8');204 }205 return preg_replace($asource, $atarget, $input);206 }207 /**208 * Returns the normalized number from a localized one209 * Parsing depends on given locale (grouping and decimal)210 *211 * Examples for input:212 * '2345.4356,1234' = 23455456.1234213 * '+23,3452.123' = 233452.123214 * '12343 ' = 12343215 * '-9456' = -9456216 * '0' = 0217 *218 * @param string $input Input string to parse for numbers219 * @param array $options Options: locale, precision. See {@link setOptions()} for details.220 * @return string Returns the extracted number221 * @throws Zend_Locale_Exception222 */223 public static function getNumber($input, array $options = array())224 {225 $options = self::_checkOptions($options) + self::$_options;226 if (!is_string($input)) {227 return $input;228 }229 if (!self::isNumber($input, $options)) {230 #require_once 'Zend/Locale/Exception.php';231 throw new Zend_Locale_Exception('No localized value in ' . $input . ' found, or the given number does not match the localized format');232 }233 // Get correct signs for this locale234 $symbols = Zend_Locale_Data::getList($options['locale'],'symbols');235 // Change locale input to be default number236 if (($input[0] == $symbols['minus']) && ('-' != $input[0])) {237 $input = '-' . substr($input, 1);238 }239 $input = str_replace($symbols['group'],'', $input);240 if (strpos($input, $symbols['decimal']) !== false) {241 if ($symbols['decimal'] != '.') {242 $input = str_replace($symbols['decimal'], ".", $input);243 }244 $pre = substr($input, strpos($input, '.') + 1);245 if ($options['precision'] === null) {246 $options['precision'] = strlen($pre);247 }248 if (strlen($pre) >= $options['precision']) {249 $input = substr($input, 0, strlen($input) - strlen($pre) + $options['precision']);250 }251 if (($options['precision'] == 0) && ($input[strlen($input) - 1] == '.')) {252 $input = substr($input, 0, -1);253 }254 }255 return $input;256 }257 /**258 * Returns a locale formatted number depending on the given options.259 * The seperation and fraction sign is used from the set locale.260 * ##0.# -> 12345.12345 -> 12345.12345261 * ##0.00 -> 12345.12345 -> 12345.12262 * ##,##0.00 -> 12345.12345 -> 12,345.12263 *264 * @param string $value Localized number string265 * @param array $options Options: number_format, locale, precision. See {@link setOptions()} for details.266 * @return string locale formatted number267 * @throws Zend_Locale_Exception268 */269 public static function toNumber($value, array $options = array())270 {271 // load class within method for speed272 #require_once 'Zend/Locale/Math.php';273 $value = Zend_Locale_Math::floatalize($value);274 $value = Zend_Locale_Math::normalize($value);275 $options = self::_checkOptions($options) + self::$_options;276 $options['locale'] = (string) $options['locale'];277 // Get correct signs for this locale278 $symbols = Zend_Locale_Data::getList($options['locale'], 'symbols');279 $oenc = self::_getEncoding();280 self::_setEncoding('UTF-8');281 282 // Get format283 $format = $options['number_format'];284 if ($format === null) {285 $format = Zend_Locale_Data::getContent($options['locale'], 'decimalnumber');286 $format = self::_seperateFormat($format, $value, $options['precision']);287 if ($options['precision'] !== null) {288 $value = Zend_Locale_Math::normalize(Zend_Locale_Math::round($value, $options['precision']));289 }290 } else {291 // seperate negative format pattern when available292 $format = self::_seperateFormat($format, $value, $options['precision']);293 if (strpos($format, '.')) {294 if (is_numeric($options['precision'])) {295 $value = Zend_Locale_Math::round($value, $options['precision']);296 } else {297 if (substr($format, iconv_strpos($format, '.') + 1, 3) == '###') {298 $options['precision'] = null;299 } else {300 $options['precision'] = iconv_strlen(iconv_substr($format, iconv_strpos($format, '.') + 1,301 iconv_strrpos($format, '0') - iconv_strpos($format, '.')));302 $format = iconv_substr($format, 0, iconv_strpos($format, '.') + 1) . '###'303 . iconv_substr($format, iconv_strrpos($format, '0') + 1);304 }305 }306 } else {307 $value = Zend_Locale_Math::round($value, 0);308 $options['precision'] = 0;309 }310 $value = Zend_Locale_Math::normalize($value);311 }312 if (iconv_strpos($format, '0') === false) {313 self::_setEncoding($oenc);314 #require_once 'Zend/Locale/Exception.php';315 throw new Zend_Locale_Exception('Wrong format... missing 0');316 }317 // get number parts318 $pos = iconv_strpos($value, '.');319 if ($pos !== false) {320 if ($options['precision'] === null) {321 $precstr = iconv_substr($value, $pos + 1);322 } else {323 $precstr = iconv_substr($value, $pos + 1, $options['precision']);324 if (iconv_strlen($precstr) < $options['precision']) {325 $precstr = $precstr . str_pad("0", ($options['precision'] - iconv_strlen($precstr)), "0");326 }327 }328 } else {329 if ($options['precision'] > 0) {330 $precstr = str_pad("0", ($options['precision']), "0");331 }332 }333 if ($options['precision'] === null) {334 if (isset($precstr)) {335 $options['precision'] = iconv_strlen($precstr);336 } else {337 $options['precision'] = 0;338 }339 }340 // get fraction and format lengths341 if (strpos($value, '.') !== false) {342 $number = substr((string) $value, 0, strpos($value, '.'));343 } else {344 $number = $value;345 }346 $prec = call_user_func(Zend_Locale_Math::$sub, $value, $number, $options['precision']);347 $prec = Zend_Locale_Math::floatalize($prec);348 $prec = Zend_Locale_Math::normalize($prec);349 if (iconv_strpos($prec, '-') !== false) {350 $prec = iconv_substr($prec, 1);351 }352 if (($prec == 0) and ($options['precision'] > 0)) {353 $prec = "0.0";354 }355 if (($options['precision'] + 2) > iconv_strlen($prec)) {356 $prec = str_pad((string) $prec, $options['precision'] + 2, "0", STR_PAD_RIGHT);357 }358 if (iconv_strpos($number, '-') !== false) {359 $number = iconv_substr($number, 1);360 }361 $group = iconv_strrpos($format, ',');362 $group2 = iconv_strpos ($format, ',');363 $point = iconv_strpos ($format, '0');364 // Add fraction365 $rest = "";366 if (iconv_strpos($format, '.')) {367 $rest = iconv_substr($format, iconv_strpos($format, '.') + 1);368 $length = iconv_strlen($rest);369 for($x = 0; $x < $length; ++$x) {370 if (($rest[0] == '0') || ($rest[0] == '#')) {371 $rest = iconv_substr($rest, 1);372 }373 }374 $format = iconv_substr($format, 0, iconv_strlen($format) - iconv_strlen($rest));375 }376 if ($options['precision'] == '0') {377 if (iconv_strrpos($format, '-') != 0) {378 $format = iconv_substr($format, 0, $point)379 . iconv_substr($format, iconv_strrpos($format, '#') + 2);380 } else {381 $format = iconv_substr($format, 0, $point);382 }383 } else {384 $format = iconv_substr($format, 0, $point) . $symbols['decimal']385 . iconv_substr($prec, 2);386 }387 $format .= $rest;388 // Add seperation389 if ($group == 0) {390 // no seperation391 $format = $number . iconv_substr($format, $point);392 } else if ($group == $group2) {393 // only 1 seperation394 $seperation = ($point - $group);395 for ($x = iconv_strlen($number); $x > $seperation; $x -= $seperation) {396 if (iconv_substr($number, 0, $x - $seperation) !== "") {397 $number = iconv_substr($number, 0, $x - $seperation) . $symbols['group']398 . iconv_substr($number, $x - $seperation);399 }400 }401 $format = iconv_substr($format, 0, iconv_strpos($format, '#')) . $number . iconv_substr($format, $point);402 } else {403 // 2 seperations404 if (iconv_strlen($number) > ($point - $group)) {405 $seperation = ($point - $group);406 $number = iconv_substr($number, 0, iconv_strlen($number) - $seperation) . $symbols['group']407 . iconv_substr($number, iconv_strlen($number) - $seperation);408 if ((iconv_strlen($number) - 1) > ($point - $group + 1)) {409 $seperation2 = ($group - $group2 - 1);410 for ($x = iconv_strlen($number) - $seperation2 - 2; $x > $seperation2; $x -= $seperation2) {411 $number = iconv_substr($number, 0, $x - $seperation2) . $symbols['group']412 . iconv_substr($number, $x - $seperation2);413 }414 }415 }416 $format = iconv_substr($format, 0, iconv_strpos($format, '#')) . $number . iconv_substr($format, $point);417 }418 // set negative sign419 if (call_user_func(Zend_Locale_Math::$comp, $value, 0, $options['precision']) < 0) {420 if (iconv_strpos($format, '-') === false) {421 $format = $symbols['minus'] . $format;422 } else {423 $format = str_replace('-', $symbols['minus'], $format);424 }425 }426 self::_setEncoding($oenc);427 return (string) $format;428 }429 /**430 * @param string $format431 * @param string $value432 * @param int $precision433 * @return string434 */435 private static function _seperateFormat($format, $value, $precision)436 {437 if (iconv_strpos($format, ';') !== false) {438 if (call_user_func(Zend_Locale_Math::$comp, $value, 0, $precision) < 0) {439 $tmpformat = iconv_substr($format, iconv_strpos($format, ';') + 1);440 if ($tmpformat[0] == '(') {441 $format = iconv_substr($format, 0, iconv_strpos($format, ';'));442 } else {443 $format = $tmpformat;444 }445 } else {446 $format = iconv_substr($format, 0, iconv_strpos($format, ';'));447 }448 }449 return $format;450 }451 /**452 * Checks if the input contains a normalized or localized number453 *454 * @param string $input Localized number string455 * @param array $options Options: locale. See {@link setOptions()} for details.456 * @return boolean Returns true if a number was found457 */458 public static function isNumber($input, array $options = array())459 {460 if (!self::_getUniCodeSupport()) {461 trigger_error("Sorry, your PCRE extension does not support UTF8 which is needed for the I18N core", E_USER_NOTICE);462 }463 $options = self::_checkOptions($options) + self::$_options;464 // Get correct signs for this locale465 $symbols = Zend_Locale_Data::getList($options['locale'],'symbols');466 $regexs = Zend_Locale_Format::_getRegexForType('decimalnumber', $options);467 $regexs = array_merge($regexs, Zend_Locale_Format::_getRegexForType('scientificnumber', $options));468 if (!empty($input) && ($input[0] == $symbols['decimal'])) {469 $input = 0 . $input;470 }471 foreach ($regexs as $regex) {472 preg_match($regex, $input, $found);473 if (isset($found[0])) {474 return true;475 }476 }477 return false;478 }479 /**480 * Internal method to convert cldr number syntax into regex481 *482 * @param string $type483 * @param array $options Options: locale. See {@link setOptions()} for details.484 * @return string485 * @throws Zend_Locale_Exception486 */487 private static function _getRegexForType($type, $options)488 {489 $decimal = Zend_Locale_Data::getContent($options['locale'], $type);490 $decimal = preg_replace('/[^#0,;\.\-Ee]/u', '',$decimal);491 $patterns = explode(';', $decimal);492 if (count($patterns) == 1) {493 $patterns[1] = '-' . $patterns[0];494 }495 $symbols = Zend_Locale_Data::getList($options['locale'],'symbols');496 foreach($patterns as $pkey => $pattern) {497 $regex[$pkey] = '/^';498 $rest = 0;499 $end = null;500 if (strpos($pattern, '.') !== false) {501 $end = substr($pattern, strpos($pattern, '.') + 1);502 $pattern = substr($pattern, 0, -strlen($end) - 1);503 }504 if (strpos($pattern, ',') !== false) {505 $parts = explode(',', $pattern);506 $count = count($parts);507 foreach($parts as $key => $part) {508 switch ($part) {509 case '#':510 case '-#':511 if ($part[0] == '-') {512 $regex[$pkey] .= '[' . $symbols['minus'] . '-]{0,1}';513 } else {514 $regex[$pkey] .= '[' . $symbols['plus'] . '+]{0,1}';515 }516 if (($parts[$key + 1]) == '##0') {517 $regex[$pkey] .= '[0-9]{1,3}';518 } else if (($parts[$key + 1]) == '##') {519 $regex[$pkey] .= '[0-9]{1,2}';520 } else {521 throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 1):"' . $pattern . '"');522 }523 break;524 case '##':525 if ($parts[$key + 1] == '##0') {526 $regex[$pkey] .= '(\\' . $symbols['group'] . '{0,1}[0-9]{2})*';527 } else {528 throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 2):"' . $pattern . '"');529 }530 break;531 case '##0':532 if ($parts[$key - 1] == '##') {533 $regex[$pkey] .= '[0-9]';534 } else if (($parts[$key - 1] == '#') || ($parts[$key - 1] == '-#')) {535 $regex[$pkey] .= '(\\' . $symbols['group'] . '{0,1}[0-9]{3})*';536 } else {537 throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 3):"' . $pattern . '"');538 }539 break;540 case '#0':541 if ($key == 0) {542 $regex[$pkey] .= '[0-9]*';543 } else {544 throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 4):"' . $pattern . '"');545 }546 break;547 }548 }549 }550 if (strpos($pattern, 'E') !== false) {551 if (($pattern == '#E0') || ($pattern == '#E00')) {552 $regex[$pkey] .= '[' . $symbols['plus']. '+]{0,1}[0-9]{1,}(\\' . $symbols['decimal'] . '[0-9]{1,})*[eE][' . $symbols['plus']. '+]{0,1}[0-9]{1,}';553 } else if (($pattern == '-#E0') || ($pattern == '-#E00')) {554 $regex[$pkey] .= '[' . $symbols['minus']. '-]{0,1}[0-9]{1,}(\\' . $symbols['decimal'] . '[0-9]{1,})*[eE][' . $symbols['minus']. '-]{0,1}[0-9]{1,}';555 } else {556 throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 5):"' . $pattern . '"');557 }558 }559 if (!empty($end)) {560 if ($end == '###') {561 $regex[$pkey] .= '(\\' . $symbols['decimal'] . '{1}[0-9]{1,}){0,1}';562 } else if ($end == '###-') {563 $regex[$pkey] .= '(\\' . $symbols['decimal'] . '{1}[0-9]{1,}){0,1}[' . $symbols['minus']. '-]';564 } else {565 throw new Zend_Locale_Exception('Unsupported token for numberformat (Pos 6):"' . $pattern . '"');566 }567 }568 $regex[$pkey] .= '$/u';569 }570 return $regex;571 }572 /**573 * Alias for getNumber574 *575 * @param string $input Number to localize576 * @param array $options Options: locale, precision. See {@link setOptions()} for details.577 * @return float578 */579 public static function getFloat($input, array $options = array())580 {581 return floatval(self::getNumber($input, $options));582 }583 /**584 * Returns a locale formatted integer number585 * Alias for toNumber()586 *587 * @param string $value Number to normalize588 * @param array $options Options: locale, precision. See {@link setOptions()} for details.589 * @return string Locale formatted number590 */591 public static function toFloat($value, array $options = array())592 {593 $options['number_format'] = Zend_Locale_Format::STANDARD;594 return self::toNumber($value, $options);595 }596 /**597 * Returns if a float was found598 * Alias for isNumber()599 *600 * @param string $value Localized number string601 * @param array $options Options: locale. See {@link setOptions()} for details.602 * @return boolean Returns true if a number was found603 */604 public static function isFloat($value, array $options = array())605 {606 return self::isNumber($value, $options);607 }608 /**609 * Returns the first found integer from an string610 * Parsing depends on given locale (grouping and decimal)611 *612 * Examples for input:613 * ' 2345.4356,1234' = 23455456614 * '+23,3452.123' = 233452615 * ' 12343 ' = 12343616 * '-9456km' = -9456617 * '0' = 0618 * '(-){0,1}(\d+(\.){0,1})*(\,){0,1})\d+'619 *620 * @param string $input Input string to parse for numbers621 * @param array $options Options: locale. See {@link setOptions()} for details.622 * @return integer Returns the extracted number623 */624 public static function getInteger($input, array $options = array())625 {626 $options['precision'] = 0;627 return intval(self::getFloat($input, $options));628 }629 /**630 * Returns a localized number631 *632 * @param string $value Number to normalize633 * @param array $options Options: locale. See {@link setOptions()} for details.634 * @return string Locale formatted number635 */636 public static function toInteger($value, array $options = array())637 {638 $options['precision'] = 0;639 $options['number_format'] = Zend_Locale_Format::STANDARD;640 return self::toNumber($value, $options);641 }642 /**643 * Returns if a integer was found644 *645 * @param string $value Localized number string646 * @param array $options Options: locale. See {@link setOptions()} for details.647 * @return boolean Returns true if a integer was found648 */649 public static function isInteger($value, array $options = array())650 {651 if (!self::isNumber($value, $options)) {652 return false;653 }654 if (self::getInteger($value, $options) == self::getFloat($value, $options)) {655 return true;656 }657 return false;658 }659 /**660 * Converts a format string from PHP's date format to ISO format661 * Remember that Zend Date always returns localized string, so a month name which returns the english662 * month in php's date() will return the translated month name with this function... use 'en' as locale663 * if you are in need of the original english names664 *665 * The conversion has the following restrictions:666 * 'a', 'A' - Meridiem is not explicit upper/lowercase, you have to upper/lowercase the translated value yourself667 *668 * @param string $format Format string in PHP's date format669 * @return string Format string in ISO format670 */671 public static function convertPhpToIsoFormat($format)672 {673 if ($format === null) {674 return null;675 }676 $convert = array(677 'd' => 'dd' , 'D' => 'EE' , 'j' => 'd' , 'l' => 'EEEE',678 'N' => 'eee' , 'S' => 'SS' , 'w' => 'e' , 'z' => 'D' ,679 'W' => 'ww' , 'F' => 'MMMM', 'm' => 'MM' , 'M' => 'MMM' ,680 'n' => 'M' , 't' => 'ddd' , 'L' => 'l' , 'o' => 'YYYY',681 'Y' => 'yyyy', 'y' => 'yy' , 'a' => 'a' , 'A' => 'a' ,682 'B' => 'B' , 'g' => 'h' , 'G' => 'H' , 'h' => 'hh' ,683 'H' => 'HH' , 'i' => 'mm' , 's' => 'ss' , 'e' => 'zzzz',684 'I' => 'I' , 'O' => 'Z' , 'P' => 'ZZZZ', 'T' => 'z' ,685 'Z' => 'X' , 'c' => 'yyyy-MM-ddTHH:mm:ssZZZZ', 'r' => 'r',686 'U' => 'U',687 );688 $escaped = false;689 $inEscapedString = false;690 $converted = array();691 foreach (str_split($format) as $char) {692 if (!$escaped && $char == '\\') {693 // Next char will be escaped: let's remember it694 $escaped = true;695 } elseif ($escaped) {696 if (!$inEscapedString) {697 // First escaped string: start the quoted chunk698 $converted[] = "'";699 $inEscapedString = true;700 }701 // Since the previous char was a \ and we are in the quoted702 // chunk, let's simply add $char as it is703 $converted[] = $char;704 $escaped = false;705 } elseif ($char == "'") {706 // Single quotes need to be escaped like this707 $converted[] = "''";708 } else {709 if ($inEscapedString) {710 // Close the single-quoted chunk711 $converted[] = "'";712 $inEscapedString = false;713 }714 // Convert the unescaped char if needed715 if (isset($convert[$char])) {716 $converted[] = $convert[$char];717 } else {718 $converted[] = $char;719 }720 }721 }722 return implode($converted);723 }724 /**725 * Parse date and split in named array fields726 *727 * @param string $date Date string to parse728 * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.729 * @return array Possible array members: day, month, year, hour, minute, second, fixed, format730 * @throws Zend_Locale_Exception731 */732 private static function _parseDate($date, $options)733 {734 if (!self::_getUniCodeSupport()) {735 trigger_error("Sorry, your PCRE extension does not support UTF8 which is needed for the I18N core", E_USER_NOTICE);736 }737 $options = self::_checkOptions($options) + self::$_options;738 $test = array('h', 'H', 'm', 's', 'y', 'Y', 'M', 'd', 'D', 'E', 'S', 'l', 'B', 'I',739 'X', 'r', 'U', 'G', 'w', 'e', 'a', 'A', 'Z', 'z', 'v');740 $format = $options['date_format'];741 $number = $date; // working copy742 $result['date_format'] = $format; // save the format used to normalize $number (convenience)743 $result['locale'] = $options['locale']; // save the locale used to normalize $number (convenience)744 $oenc = self::_getEncoding();745 self::_setEncoding('UTF-8');746 $day = iconv_strpos($format, 'd');747 $month = iconv_strpos($format, 'M');748 $year = iconv_strpos($format, 'y');749 $hour = iconv_strpos($format, 'H');750 $min = iconv_strpos($format, 'm');751 $sec = iconv_strpos($format, 's');752 $am = null;753 if ($hour === false) {754 $hour = iconv_strpos($format, 'h');755 }756 if ($year === false) {757 $year = iconv_strpos($format, 'Y');758 }759 if ($day === false) {760 $day = iconv_strpos($format, 'E');761 if ($day === false) {762 $day = iconv_strpos($format, 'D');763 }764 }765 if ($day !== false) {766 $parse[$day] = 'd';767 if (!empty($options['locale']) && ($options['locale'] !== 'root') &&768 (!is_object($options['locale']) || ((string) $options['locale'] !== 'root'))) {769 // erase day string770 $daylist = Zend_Locale_Data::getList($options['locale'], 'day');771 foreach($daylist as $key => $name) {772 if (iconv_strpos($number, $name) !== false) {773 $number = str_replace($name, "EEEE", $number);774 break;775 }776 }777 }778 }779 $position = false;780 if ($month !== false) {781 $parse[$month] = 'M';782 if (!empty($options['locale']) && ($options['locale'] !== 'root') &&783 (!is_object($options['locale']) || ((string) $options['locale'] !== 'root'))) {784 // prepare to convert month name to their numeric equivalents, if requested,785 // and we have a $options['locale']786 $position = self::_replaceMonth($number, Zend_Locale_Data::getList($options['locale'],787 'month'));788 if ($position === false) {789 $position = self::_replaceMonth($number, Zend_Locale_Data::getList($options['locale'],790 'month', array('gregorian', 'format', 'abbreviated')));791 }792 }793 }794 if ($year !== false) {795 $parse[$year] = 'y';796 }797 if ($hour !== false) {798 $parse[$hour] = 'H';799 }800 if ($min !== false) {801 $parse[$min] = 'm';802 }803 if ($sec !== false) {804 $parse[$sec] = 's';805 }806 if (empty($parse)) {807 self::_setEncoding($oenc);808 #require_once 'Zend/Locale/Exception.php';809 throw new Zend_Locale_Exception("Unknown date format, neither date nor time in '" . $format . "' found");810 }811 ksort($parse);812 // get daytime813 if (iconv_strpos($format, 'a') !== false) {814 if (iconv_strpos(strtoupper($number), strtoupper(Zend_Locale_Data::getContent($options['locale'], 'am'))) !== false) {815 $am = true;816 } else if (iconv_strpos(strtoupper($number), strtoupper(Zend_Locale_Data::getContent($options['locale'], 'pm'))) !== false) {817 $am = false;818 }819 }820 // split number parts821 $split = false;822 preg_match_all('/\d+/u', $number, $splitted);823 if (count($splitted[0]) == 0) {824 self::_setEncoding($oenc);825 #require_once 'Zend/Locale/Exception.php';826 throw new Zend_Locale_Exception("No date part in '$date' found.");827 }828 if (count($splitted[0]) == 1) {829 $split = 0;830 }831 $cnt = 0;832 foreach($parse as $key => $value) {833 switch($value) {834 case 'd':835 if ($split === false) {836 if (count($splitted[0]) > $cnt) {837 $result['day'] = $splitted[0][$cnt];838 }839 } else {840 $result['day'] = iconv_substr($splitted[0][0], $split, 2);841 $split += 2;842 }843 ++$cnt;844 break;845 case 'M':846 if ($split === false) {847 if (count($splitted[0]) > $cnt) {848 $result['month'] = $splitted[0][$cnt];849 }850 } else {851 $result['month'] = iconv_substr($splitted[0][0], $split, 2);852 $split += 2;853 }854 ++$cnt;855 break;856 case 'y':857 $length = 2;858 if ((iconv_substr($format, $year, 4) == 'yyyy')859 || (iconv_substr($format, $year, 4) == 'YYYY')) {860 $length = 4;861 }862 if ($split === false) {863 if (count($splitted[0]) > $cnt) {864 $result['year'] = $splitted[0][$cnt];865 }866 } else {867 $result['year'] = iconv_substr($splitted[0][0], $split, $length);868 $split += $length;869 }870 ++$cnt;871 break;872 case 'H':873 if ($split === false) {874 if (count($splitted[0]) > $cnt) {875 $result['hour'] = $splitted[0][$cnt];876 }877 } else {878 $result['hour'] = iconv_substr($splitted[0][0], $split, 2);879 $split += 2;880 }881 ++$cnt;882 break;883 case 'm':884 if ($split === false) {885 if (count($splitted[0]) > $cnt) {886 $result['minute'] = $splitted[0][$cnt];887 }888 } else {889 $result['minute'] = iconv_substr($splitted[0][0], $split, 2);890 $split += 2;891 }892 ++$cnt;893 break;894 case 's':895 if ($split === false) {896 if (count($splitted[0]) > $cnt) {897 $result['second'] = $splitted[0][$cnt];898 }899 } else {900 $result['second'] = iconv_substr($splitted[0][0], $split, 2);901 $split += 2;902 }903 ++$cnt;904 break;905 }906 }907 // AM/PM correction908 if ($hour !== false) {909 if (($am === true) and ($result['hour'] == 12)){910 $result['hour'] = 0;911 } else if (($am === false) and ($result['hour'] != 12)) {912 $result['hour'] += 12;913 }914 }915 if ($options['fix_date'] === true) {916 $result['fixed'] = 0; // nothing has been "fixed" by swapping date parts around (yet)917 }918 if ($day !== false) {919 // fix false month920 if (isset($result['day']) and isset($result['month'])) {921 if (($position !== false) and ((iconv_strpos($date, $result['day']) === false) or922 (isset($result['year']) and (iconv_strpos($date, $result['year']) === false)))) {923 if ($options['fix_date'] !== true) {924 self::_setEncoding($oenc);925 #require_once 'Zend/Locale/Exception.php';926 throw new Zend_Locale_Exception("Unable to parse date '$date' using '" . $format927 . "' (false month, $position, $month)");928 }929 $temp = $result['day'];930 $result['day'] = $result['month'];931 $result['month'] = $temp;932 $result['fixed'] = 1;933 }934 }935 // fix switched values d <> y936 if (isset($result['day']) and isset($result['year'])) {937 if ($result['day'] > 31) {938 if ($options['fix_date'] !== true) {939 self::_setEncoding($oenc);940 #require_once 'Zend/Locale/Exception.php';941 throw new Zend_Locale_Exception("Unable to parse date '$date' using '"942 . $format . "' (d <> y)");943 }944 $temp = $result['year'];945 $result['year'] = $result['day'];946 $result['day'] = $temp;947 $result['fixed'] = 2;948 }949 }950 // fix switched values M <> y951 if (isset($result['month']) and isset($result['year'])) {952 if ($result['month'] > 31) {953 if ($options['fix_date'] !== true) {954 self::_setEncoding($oenc);955 #require_once 'Zend/Locale/Exception.php';956 throw new Zend_Locale_Exception("Unable to parse date '$date' using '"957 . $format . "' (M <> y)");958 }959 $temp = $result['year'];960 $result['year'] = $result['month'];961 $result['month'] = $temp;962 $result['fixed'] = 3;963 }964 }965 // fix switched values M <> d966 if (isset($result['month']) and isset($result['day'])) {967 if ($result['month'] > 12) {968 if ($options['fix_date'] !== true || $result['month'] > 31) {969 self::_setEncoding($oenc);970 #require_once 'Zend/Locale/Exception.php';971 throw new Zend_Locale_Exception("Unable to parse date '$date' using '"972 . $format . "' (M <> d)");973 }974 $temp = $result['day'];975 $result['day'] = $result['month'];976 $result['month'] = $temp;977 $result['fixed'] = 4;978 }979 }980 }981 if (isset($result['year'])) {982 if (((iconv_strlen($result['year']) == 2) && ($result['year'] < 10)) ||983 (((iconv_strpos($format, 'yy') !== false) && (iconv_strpos($format, 'yyyy') === false)) ||984 ((iconv_strpos($format, 'YY') !== false) && (iconv_strpos($format, 'YYYY') === false)))) {985 if (($result['year'] >= 0) && ($result['year'] < 100)) {986 if ($result['year'] < 70) {987 $result['year'] = (int) $result['year'] + 100;988 }989 $result['year'] = (int) $result['year'] + 1900;990 }991 }992 }993 self::_setEncoding($oenc);994 return $result;995 }996 /**997 * Search $number for a month name found in $monthlist, and replace if found.998 *999 * @param string $number Date string (modified)1000 * @param array $monthlist List of month names1001 *1002 * @return int|false Position of replaced string (false if nothing replaced)1003 */1004 protected static function _replaceMonth(&$number, $monthlist)1005 {1006 // If $locale was invalid, $monthlist will default to a "root" identity1007 // mapping for each month number from 1 to 12.1008 // If no $locale was given, or $locale was invalid, do not use this identity mapping to normalize.1009 // Otherwise, translate locale aware month names in $number to their numeric equivalents.1010 $position = false;1011 if ($monthlist && $monthlist[1] != 1) {1012 foreach($monthlist as $key => $name) {1013 if (($position = iconv_strpos($number, $name, 0, 'UTF-8')) !== false) {1014 $number = str_ireplace($name, $key, $number);1015 return $position;1016 }1017 }1018 }1019 return false;1020 }1021 /**1022 * Returns the default date format for $locale.1023 *1024 * @param string|Zend_Locale $locale OPTIONAL Locale of $number, possibly in string form (e.g. 'de_AT')1025 * @return string format1026 * @throws Zend_Locale_Exception throws an exception when locale data is broken1027 */1028 public static function getDateFormat($locale = null)1029 {1030 $format = Zend_Locale_Data::getContent($locale, 'date');1031 if (empty($format)) {1032 #require_once 'Zend/Locale/Exception.php';1033 throw new Zend_Locale_Exception("failed to receive data from locale $locale");1034 }1035 return $format;1036 }1037 /**1038 * Returns an array with the normalized date from an locale date1039 * a input of 10.01.2006 without a $locale would return:1040 * array ('day' => 10, 'month' => 1, 'year' => 2006)1041 * The 'locale' option is only used to convert human readable day1042 * and month names to their numeric equivalents.1043 * The 'format' option allows specification of self-defined date formats,1044 * when not using the default format for the 'locale'.1045 *1046 * @param string $date Date string1047 * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.1048 * @return array Possible array members: day, month, year, hour, minute, second, fixed, format1049 */1050 public static function getDate($date, array $options = array())1051 {1052 $options = self::_checkOptions($options) + self::$_options;1053 if (empty($options['date_format'])) {1054 $options['format_type'] = 'iso';1055 $options['date_format'] = self::getDateFormat($options['locale']);1056 }1057 return self::_parseDate($date, $options);1058 }1059 /**1060 * Returns if the given datestring contains all date parts from the given format.1061 * If no format is given, the default date format from the locale is used1062 * If you want to check if the date is a proper date you should use Zend_Date::isDate()1063 *1064 * @param string $date Date string1065 * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.1066 * @return boolean1067 */1068 public static function checkDateFormat($date, array $options = array())1069 {1070 try {1071 $date = self::getDate($date, $options);1072 } catch (Exception $e) {1073 return false;1074 }1075 if (empty($options['date_format'])) {1076 $options['format_type'] = 'iso';1077 $options['date_format'] = self::getDateFormat(isset($options['locale']) ? $options['locale'] : null);1078 }1079 $options = self::_checkOptions($options) + self::$_options;1080 // day expected but not parsed1081 if ((iconv_strpos($options['date_format'], 'd', 0, 'UTF-8') !== false) and (!isset($date['day']) or ($date['day'] === ""))) {1082 return false;1083 }1084 // month expected but not parsed1085 if ((iconv_strpos($options['date_format'], 'M', 0, 'UTF-8') !== false) and (!isset($date['month']) or ($date['month'] === ""))) {1086 return false;1087 }1088 // year expected but not parsed1089 if (((iconv_strpos($options['date_format'], 'Y', 0, 'UTF-8') !== false) or1090 (iconv_strpos($options['date_format'], 'y', 0, 'UTF-8') !== false)) and (!isset($date['year']) or ($date['year'] === ""))) {1091 return false;1092 }1093 // second expected but not parsed1094 if ((iconv_strpos($options['date_format'], 's', 0, 'UTF-8') !== false) and (!isset($date['second']) or ($date['second'] === ""))) {1095 return false;1096 }1097 // minute expected but not parsed1098 if ((iconv_strpos($options['date_format'], 'm', 0, 'UTF-8') !== false) and (!isset($date['minute']) or ($date['minute'] === ""))) {1099 return false;1100 }1101 // hour expected but not parsed1102 if (((iconv_strpos($options['date_format'], 'H', 0, 'UTF-8') !== false) or1103 (iconv_strpos($options['date_format'], 'h', 0, 'UTF-8') !== false)) and (!isset($date['hour']) or ($date['hour'] === ""))) {1104 return false;1105 }1106 return true;1107 }1108 /**1109 * Returns the default time format for $locale.1110 *1111 * @param string|Zend_Locale $locale OPTIONAL Locale of $number, possibly in string form (e.g. 'de_AT')1112 * @return string format1113 * @throws Zend_Locale_Exception1114 */1115 public static function getTimeFormat($locale = null)1116 {1117 $format = Zend_Locale_Data::getContent($locale, 'time');1118 if (empty($format)) {1119 #require_once 'Zend/Locale/Exception.php';1120 throw new Zend_Locale_Exception("failed to receive data from locale $locale");1121 }1122 return $format;1123 }1124 /**1125 * Returns an array with 'hour', 'minute', and 'second' elements extracted from $time1126 * according to the order described in $format. For a format of 'H:i:s', and1127 * an input of 11:20:55, getTime() would return:1128 * array ('hour' => 11, 'minute' => 20, 'second' => 55)1129 * The optional $locale parameter may be used to help extract times from strings1130 * containing both a time and a day or month name.1131 *1132 * @param string $time Time string1133 * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.1134 * @return array Possible array members: day, month, year, hour, minute, second, fixed, format1135 */1136 public static function getTime($time, array $options = array())1137 {1138 $options = self::_checkOptions($options) + self::$_options;1139 if (empty($options['date_format'])) {1140 $options['format_type'] = 'iso';1141 $options['date_format'] = self::getTimeFormat($options['locale']);1142 }1143 return self::_parseDate($time, $options);1144 }1145 /**1146 * Returns the default datetime format for $locale.1147 *1148 * @param string|Zend_Locale $locale OPTIONAL Locale of $number, possibly in string form (e.g. 'de_AT')1149 * @return string format1150 * @throws Zend_Locale_Exception1151 */1152 public static function getDateTimeFormat($locale = null)1153 {1154 $format = Zend_Locale_Data::getContent($locale, 'datetime');1155 if (empty($format)) {1156 #require_once 'Zend/Locale/Exception.php';1157 throw new Zend_Locale_Exception("failed to receive data from locale $locale");1158 }1159 return $format;1160 }1161 /**1162 * Returns an array with 'year', 'month', 'day', 'hour', 'minute', and 'second' elements1163 * extracted from $datetime according to the order described in $format. For a format of 'd.M.y H:i:s',1164 * and an input of 10.05.1985 11:20:55, getDateTime() would return:1165 * array ('year' => 1985, 'month' => 5, 'day' => 10, 'hour' => 11, 'minute' => 20, 'second' => 55)1166 * The optional $locale parameter may be used to help extract times from strings1167 * containing both a time and a day or month name.1168 *1169 * @param string $datetime DateTime string1170 * @param array $options Options: format_type, fix_date, locale, date_format. See {@link setOptions()} for details.1171 * @return array Possible array members: day, month, year, hour, minute, second, fixed, format1172 */1173 public static function getDateTime($datetime, array $options = array())1174 {1175 $options = self::_checkOptions($options) + self::$_options;1176 if (empty($options['date_format'])) {1177 $options['format_type'] = 'iso';1178 $options['date_format'] = self::getDateTimeFormat($options['locale']);1179 }1180 return self::_parseDate($datetime, $options);1181 }1182 /**1183 * Internal method to detect of Unicode supports UTF81184 * which should be enabled within vanilla php installations1185 *1186 * @return boolean1187 */1188 protected static function _getUniCodeSupport()1189 {1190 return (@preg_match('/\pL/u', 'a')) ? true : false;1191 }1192 /**...
format
Using AI Code Generation
1$fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);2echo $fmt->format(123456.789);3$fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);4echo $fmt->formatCurrency(123456.789, "USD");5$fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);6echo $fmt->formatCurrency(123456.789, "USD");7echo $fmt->formatCurrency(123456.789, "INR");8echo $fmt->formatCurrency(123456.789, "GBP");9echo $fmt->formatCurrency(123456.789, "EUR");10$fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);11echo $fmt->formatCurrency(123456.789, "USD");12echo $fmt->formatCurrency(123456.789, "INR");13echo $fmt->formatCurrency(123456.789, "GBP");14echo $fmt->formatCurrency(123456.789, "EUR");15echo $fmt->formatCurrency(123456.789, "AUD");16$fmt = new NumberFormatter('en_US', NumberFormatter::CURRENCY);17echo $fmt->formatCurrency(123456.789, "USD");18echo $fmt->formatCurrency(123456.789, "INR");19echo $fmt->formatCurrency(123456.789, "GBP");20echo $fmt->formatCurrency(123456.789, "EUR");21echo $fmt->formatCurrency(123456.789,
format
Using AI Code Generation
1$fmt = new NumberFormatter( "en_US", NumberFormatter::DECIMAL );2$fmt = new NumberFormatter( "fr_FR", NumberFormatter::DECIMAL );3$fmt = new NumberFormatter( "de_DE", NumberFormatter::DECIMAL );4$fmt = new NumberFormatter( "de_DE", NumberFormatter::DECIMAL );5$fmt = new NumberFormatter( "de_DE", NumberFormatter::DECIMAL );6$fmt = new NumberFormatter( "de_DE", NumberFormatter::DECIMAL );7$fmt = new NumberFormatter( "de_DE", NumberFormatter::DECIMAL );8$fmt = new NumberFormatter( "de_DE", NumberFormatter::DECIMAL );9$fmt = new NumberFormatter(
format
Using AI Code Generation
1$fmt = new NumberFormatter( "en", NumberFormatter::DECIMAL );2echo $fmt->format( 1234.56 );3$fmt = new NumberFormatter( "en", NumberFormatter::PERCENT );4echo $fmt->format( 0.75 );5$fmt = new NumberFormatter( "en", NumberFormatter::SCIENTIFIC );6echo $fmt->format( 1234.56 );7$fmt = new NumberFormatter( "en", NumberFormatter::CURRENCY );8echo $fmt->format( 1234.56 );9$fmt = new NumberFormatter( "en", NumberFormatter::CURRENCY );10echo $fmt->format( 1234.56 );11$fmt = new NumberFormatter( "en", NumberFormatter::CURRENCY );12echo $fmt->format( 1234.56 );13$fmt = new NumberFormatter( "en", NumberFormatter::CURRENCY );14echo $fmt->format( 1234.56 );15$fmt = new NumberFormatter( "en", NumberFormatter::CURRENCY );16echo $fmt->format( 1234.56 );17$fmt = new NumberFormatter( "en", NumberFormatter::CURRENCY );18echo $fmt->format( 1234.56 );
format
Using AI Code Generation
1$fmt = new NumberFormatter( "en_IN", NumberFormatter::CURRENCY );2echo $fmt->format( 123456789.123456789 ) . "3";4$fmt = new NumberFormatter( "en_IN", NumberFormatter::CURRENCY );5echo $fmt->formatCurrency(123456789.123456789, "INR") . "6";7PHP | NumberFormatter::getErrorCode() Function8PHP | NumberFormatter::getErrorMessage() Function9PHP | NumberFormatter::setSymbol() Function10PHP | NumberFormatter::setPattern() Function11PHP | NumberFormatter::getSymbol() Function12PHP | NumberFormatter::getPattern() Function13PHP | NumberFormatter::formatCurrency() Function14PHP | NumberFormatter::setSymbol() Function15PHP | NumberFormatter::setPattern() Function16PHP | NumberFormatter::getSymbol() Function17PHP | NumberFormatter::getPattern() Function18PHP | NumberFormatter::formatCurrency() Function19PHP | NumberFormatter::getErrorCode() Function20PHP | NumberFormatter::getErrorMessage() Function21PHP | NumberFormatter::setSymbol() Function22PHP | NumberFormatter::setPattern() Function23PHP | NumberFormatter::getSymbol() Function24PHP | NumberFormatter::getPattern() Function25PHP | NumberFormatter::formatCurrency() Function26PHP | NumberFormatter::getErrorCode() Function27PHP | NumberFormatter::getErrorMessage() Function28PHP | NumberFormatter::setSymbol() Function29PHP | NumberFormatter::setPattern() Function30PHP | NumberFormatter::getSymbol() Function31PHP | NumberFormatter::getPattern() Function32PHP | NumberFormatter::formatCurrency() Function33PHP | NumberFormatter::getErrorCode() Function34PHP | NumberFormatter::getErrorMessage() Function35PHP | NumberFormatter::setSymbol() Function36PHP | NumberFormatter::setPattern() Function37PHP | NumberFormatter::getSymbol() Function38PHP | NumberFormatter::getPattern() Function39PHP | NumberFormatter::formatCurrency() Function40PHP | NumberFormatter::getErrorCode() Function41PHP | NumberFormatter::getErrorMessage() Function42PHP | NumberFormatter::setSymbol() Function43PHP | NumberFormatter::setPattern() Function44PHP | NumberFormatter::getSymbol() Function45PHP | NumberFormatter::getPattern() Function
format
Using AI Code Generation
1setlocale(LC_MONETARY, "en_US");2echo money_format("%i", 123456.78) . "3";4echo money_format("%i", 123456) . "5";6echo money_format("%i", -123456.78) . "7";8echo money_format("%i", -123456) . "9";10echo money_format("%i", 123456.78) . "11";12echo money_format("%i", 123456) . "13";14echo money_format("%i", -123456.78) . "15";16echo money_format("%i", -123456) . "17";
format
Using AI Code Generation
1$locale = new Zend_Locale('en_US');2$currency = new Zend_Currency('en_US');3$currency->setFormat(array('position' => 'right',4'format' => Zend_Currency::STANDARD));5$currency->setValue('1000');6echo $currency->toCurrency();7$locale = new Zend_Locale('en_US');8$currency = new Zend_Currency('en_US');9$currency->setValue('1000');10echo $currency->toCurrency();11$locale = new Zend_Locale('en_US');12$currency = new Zend_Currency('en_US');13$currency->setValue('1000');14$currency->setFormat(array('position' => 'right',15'format' => Zend_Currency::STANDARD));16echo $currency->toCurrency();17$locale = new Zend_Locale('en_US');18$currency = new Zend_Currency('en_US');19$currency->setValue('1000');20echo $currency->toCurrency();
format
Using AI Code Generation
1$locale = new Locale('en', 'EN');2echo $locale->format('%.2f', 123.456);3$locale = new Locale('en', 'EN');4echo $locale->format('%.2f', 123.456, array('grouping' => FALSE));5$locale = new Locale('en', 'EN');6echo $locale->format('%.2f', 123.456, array('grouping' => TRUE));7$locale = new Locale('en', 'EN');8echo $locale->format('%.2f', 123.456, array('grouping' => TRUE, 'type' => 'standard'));9$locale = new Locale('en', 'EN');10echo $locale->format('%.2f', 123.456, array('grouping' => TRUE, 'type' => 'accounting'));11$locale = new Locale('en', 'EN');12echo $locale->format('%.2f', 123.456, array('grouping' => TRUE, 'type' => 'scientific'));13$locale = new Locale('en', 'EN');14echo $locale->format('%.2f', 123.456, array('grouping' => TRUE, 'type' => 'engineering'));15$locale = new Locale('en', 'EN');16echo $locale->format('%.2f', 123.456, array('grouping' => TRUE, 'type' => 'spellout'));
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Execute automation tests with format on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.
Test now for FreeGet 100 minutes of automation test minutes FREE!!