Function format - Format Phone Number

@author: 713uk13m <dev@nguyenanhung.com>
@time  : 9/28/18 13:40

@param string $my_number
@param string $my_format

@return mixed|null|string
@throws \Exception
174444
public function format($my_number = '', $my_format = '')
    {
        if (empty($my_number)) {
            return NULL;
        }
        try {
            $phoneNumber = new PhoneNumber();
            $phoneNumber->setDebugStatus($this->DEBUG);
            $phoneNumber->setLoggerPath($this->loggerPath);
            $phoneNumber->__construct();
            $result = $phoneNumber->format(trim($my_number), trim($my_format));
            $this->_debug->info(__FUNCTION__, 'Result: ' . $result);

            return $result;
        }
        catch (\Exception $e) {
            $message = 'Error File: ' . $e->getFile() . ' - Line: ' . $e->getLine() . ' - Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage();
            if (function_exists('log_message')) {
                log_message('error', $message);
            }
            $this->_debug->error(__FUNCTION__, $message);

            return $my_number;
        }
    }
996501
public function format(int $format) : string
    {
        return PhoneNumberUtil::getInstance()->format($this->phoneNumber, $format);
    }
457486
public function set_num_format($num_format) {
        $numbers = array();

        $numbers[1] = '0';
        $numbers[2] = '0.00';
        $numbers[3] = '#,##0';
        $numbers[4] = '#,##0.00';
        $numbers[11] = '0.00E+00';
        $numbers[12] = '# ?/?';
        $numbers[13] = '# ??/??';
        $numbers[14] = 'mm-dd-yy';
        $numbers[15] = 'd-mmm-yy';
        $numbers[16] = 'd-mmm';
        $numbers[17] = 'mmm-yy';
        $numbers[22] = 'm/d/yy h:mm';
        $numbers[49] = '@';

        if ($num_format !== 0 and in_array($num_format, $numbers)) {
            $this->format['numberformat']['code'] = $num_format;
        }

        if (!isset($numbers[$num_format])) {
            return;
        }

        $this->format['numberformat']['code'] = $numbers[$num_format];
    }
1211476
public function formatMsisdn($phone_number = '', $format = NULL)
    {
        if (empty($phone_number)) {
            return NULL;
        }
        try {
            if (mb_strpos('*', $phone_number) || mb_strpos('x', $phone_number)) {
                return $phone_number;
            } else {
                if (self::MSISDN_FORMAT_MODE == 'new' || self::MSISDN_FORMAT_MODE == 'old') {
                    $BasePhoneNumber = new BasePhoneNumber();
                    $phone_number    = $BasePhoneNumber->phone_number_convert($phone_number, self::MSISDN_FORMAT_MODE, $format);
                } else {
                    $phone_number = $this->phoneNumber->format($phone_number, $format);
                }

                return $phone_number;
            }
        }
        catch (\Exception $e) {
            return $phone_number;
        }
    }
1224633
@RequestMapping(value = PhoneNumber.PARSE_AND_FORMAT, method = RequestMethod.GET)
  @PermitAll
  public PhoneNumberDataWithFormats parseAndFormatPhoneNumber(
      @RequestParam(value = Parameters.LANGUAGE, required = true) final String planguage,
      @RequestParam(value = Parameters.COUNTRY, required = true) final String pcountry,
      @RequestParam(value = Parameters.PHONE_NUMBER, required = true) final String pphoneNumber) {
    final PhoneNumberDataWithFormats result = new PhoneNumberDataWithFormats(phoneNumberUtil
        .parsePhoneNumber(pphoneNumber, pcountry, LocaleUtil.convertLanguageToLocale(planguage)));
    result.setCommonInternational(phoneNumberUtil.formatCommonInternational(result));
    result.setCommonNational(phoneNumberUtil.formatCommonNational(result));
    result.setDin5008International(phoneNumberUtil.formatDin5008International(result));
    result.setDin5008National(phoneNumberUtil.formatDin5008National(result));
    result.setE123International(phoneNumberUtil.formatE123International(result));
    result.setE123National(phoneNumberUtil.formatE123National(result));
    result.setMs(phoneNumberUtil.formatMs(result));
    result.setUrl(phoneNumberUtil.formatUrl(result));
    return result;
  }
265322
public static function formatSocialNumber($number){

		assert('is_integer($number)');

		if(!is_integer($number)) return $number;

		if($number > 10000000){

			$number = round($number / 1000000) . 'M';
		}
		elseif($number > 1000000){

			$number = round($number / 1000000, 1) . 'M';
		}
		elseif($number > 10000){

			$number = round($number / 1000) . 'K';
		}
		elseif($number > 1000){

			$number = round($number / 1000, 1) . 'K';
		}

		return $number;
	}
487109
public function numberFormat()
    {
        $num = (float) ((string) $this->getRequiredParameter('number'));
        $decimals = intval((string)$this->getParameter('decimals'));
        return number_format($num, $decimals);
    }
1229376
function _createFormat() {
    $objectname                   = null;
    switch( $this->format ) {
      case 'xcal':
        $objectname               = ( isset( $this->timezonetype )) ?
                                 strtolower( $this->timezonetype )  :  strtolower( $this->objName );
        $this->componentStart1    = $this->elementStart1 = '<';
        $this->componentStart2    = $this->elementStart2 = '>';
        $this->componentEnd1      = $this->elementEnd1   = '</';
        $this->componentEnd2      = $this->elementEnd2   = '>'.$this->nl;
        $this->intAttrDelimiter   = '<!-- -->';
        $this->attributeDelimiter = $this->nl;
        $this->valueInit          = null;
        break;
      default:
        $objectname               = ( isset( $this->timezonetype )) ?
                                 strtoupper( $this->timezonetype )  :  strtoupper( $this->objName );
        $this->componentStart1    = 'BEGIN:';
        $this->componentStart2    = null;
        $this->componentEnd1      = 'END:';
        $this->componentEnd2      = $this->nl;
        $this->elementStart1      = null;
        $this->elementStart2      = null;
        $this->elementEnd1        = null;
        $this->elementEnd2        = $this->nl;
        $this->intAttrDelimiter   = '<!-- -->';
        $this->attributeDelimiter = ';';
        $this->valueInit          = ':';
        break;
    }
    return $objectname;
  }
815064
public function format($number, ArrayObject $row = null): string
    {
        $locale = $this->params['locale'];

        //$formatterId = md5($locale);
        $formatterId = $locale . (string) $this->params['pattern'];

        if (!array_key_exists($formatterId, $this->formatters)) {
            $this->loadFormatterId($formatterId);
        }

        if ($this->currency_column !== null) {
            if (!isset($row[$this->currency_column])) {
                throw new Exception\RuntimeException(__METHOD__ . " Cannot determine currency code based on column '{$this->currency_column}'.");
            }
            $value = $this->formatters[$formatterId]->formatCurrency(
                (float) $number,
                $row[$this->currency_column]
            );
        } else {
            if ($this->params['currency_code'] == '') {
                throw new Exception\RuntimeException(__METHOD__ . ' Currency code must be set prior to use the currency formatter');
            }

            $value = $this->formatters[$formatterId]->formatCurrency(
                (float) $number,
                $this->params['currency_code']
            );
        }

        if (intl_is_failure($this->formatters[$formatterId]->getErrorCode())) {
            $this->throwNumberFormatterException($this->formatters[$formatterId], $number);
        }

        return $value;
    }
1093378
public static function formatted($numValue, $deci = 0, $sep = ' ', $dec_point = ',')
    {
        if ($numValue == '') {
            return '';
        }
        
        return number_format($numValue, $deci, $dec_point, $sep);
    }
1079967
static public function buildFormatRand($format,$number=1) {
        $str  =  array();
        $length =  strlen($format);
        for($j=0; $j<$number; $j++) {
            $strtemp   = '';
            for($i=0; $i<$length; $i++) {
                $char = substr($format,$i,1);
                switch($char){
                    case "*"://字母和数字混合
                        $strtemp   .= String::randString(1);
                        break;
                    case "#"://数字
                        $strtemp  .= String::randString(1,1);
                        break;
                    case "$"://大写字母
                        $strtemp .=  String::randString(1,2);
                        break;
                    default://其他格式均不转换
                        $strtemp .=   $char;
                        break;
               }
            }
            $str[] = $strtemp;
        }
        return $number==1? $strtemp : $str ;
    }
452238
private static function numberFormatStandardized($num_format)
    {
        if ($num_format == 'money') {
            $num_format = 'dollar';
        }
        if ($num_format == 'number') {
            $num_format = 'integer';
        }

        if ($num_format == 'string') {
            $num_format = '@';
        } else {
            if ($num_format == 'integer') {
                $num_format = '0';
            } else {
                if ($num_format == 'date') {
                    $num_format = 'YYYY-MM-DD';
                } else {
                    if ($num_format == 'datetime') {
                        $num_format = 'YYYY-MM-DD HH:MM:SS';
                    } else {
                        if ($num_format == 'price') {
                            $num_format = '#,##0.00';
                        } else {
                            if ($num_format == 'dollar') {
                                $num_format = '[$$-1009]#,##0.00;[RED]-[$$-1009]#,##0.00';
                            } else {
                                if ($num_format == 'euro') {
                                    $num_format = '#,##0.00 [$€-407];[RED]-#,##0.00 [$€-407]';
                                }
                            }
                        }
                    }
                }
            }
        }
        $ignore_until = '';
        $escaped = '';
        for ($i = 0, $ix = strlen($num_format); $i < $ix; $i++) {
            $c = $num_format[$i];
            if ($ignore_until == '' && $c == '[') {
                $ignore_until = ']';
            } else {
                if ($ignore_until == '' && $c == '"') {
                    $ignore_until = '"';
                } else {
                    if ($ignore_until == $c) {
                        $ignore_until = '';
                    }
                }
            }
            if ($ignore_until == '' && ($c == ' ' || $c == '-' || $c == '(' || $c == ')') && ($i == 0 || $num_format[$i - 1] != '_')) {
                $escaped .= "\\" . $c;
            } else {
                $escaped .= $c;
            }
        }
        return $escaped;
    }
12934
function format() {
		$args=func_get_args();
		$val=array_shift($args);
		// Get formatting rules
		$conv=localeconv();
		return preg_replace_callback(
			'/\{(?P<pos>\d+)\s*(?:,\s*(?P<type>\w+)\s*'.
			'(?:,\s*(?P<mod>(?:\w+(?:\s*\{.+?\}\s*,?)?)*)'.
			'(?:,\s*(?P<prop>.+?))?)?)?\}/',
			function($expr) use($args,$conv) {
				extract($expr);
				extract($conv);
				if (!array_key_exists($pos,$args))
					return $expr[0];
				if (isset($type))
					switch ($type) {
						case 'plural':
							preg_match_all('/(?<tag>\w+)'.
								'(?:\s*\{\s*(?<data>.+?)\s*\})/',
								$mod,$matches,PREG_SET_ORDER);
							$ord=array('zero','one','two');
							foreach ($matches as $match) {
								extract($match);
								if (isset($ord[$args[$pos]]) &&
									$tag==$ord[$args[$pos]] || $tag=='other')
									return str_replace('#',$args[$pos],$data);
							}
						case 'number':
							if (isset($mod))
								switch ($mod) {
									case 'integer':
										return number_format(
											$args[$pos],0,'',$thousands_sep);
									case 'currency':
										if (function_exists('money_format'))
											return money_format(
												'%n',$args[$pos]);
										$fmt=array(
											0=>'(nc)',1=>'(n c)',
											2=>'(nc)',10=>'+nc',
											11=>'+n c',12=>'+ nc',
											20=>'nc+',21=>'n c+',
											22=>'nc +',30=>'n+c',
											31=>'n +c',32=>'n+ c',
											40=>'nc+',41=>'n c+',
											42=>'nc +',100=>'(cn)',
											101=>'(c n)',102=>'(cn)',
											110=>'+cn',111=>'+c n',
											112=>'+ cn',120=>'cn+',
											121=>'c n+',122=>'cn +',
											130=>'+cn',131=>'+c n',
											132=>'+ cn',140=>'c+n',
											141=>'c+ n',142=>'c +n'
										);
										if ($args[$pos]<0) {
											$sgn=$negative_sign;
											$pre='n';
										}
										else {
											$sgn=$positive_sign;
											$pre='p';
										}
										return str_replace(
											array('+','n','c'),
											array($sgn,number_format(
												abs($args[$pos]),
												$frac_digits,
												$decimal_point,
												$thousands_sep),
												$currency_symbol),
											$fmt[(int)(
												(${$pre.'_cs_precedes'}%2).
												(${$pre.'_sign_posn'}%5).
												(${$pre.'_sep_by_space'}%3)
											)]
										);
									case 'percent':
										return number_format(
											$args[$pos]*100,0,$decimal_point,
											$thousands_sep).'%';
									case 'decimal':
										return number_format(
											$args[$pos],$prop,$decimal_point,
												$thousands_sep);
								}
							break;
						case 'date':
							if (empty($mod) || $mod=='short')
								$prop='%x';
							elseif ($mod=='long')
								$prop='%A, %d %B %Y';
							return strftime($prop,$args[$pos]);
						case 'time':
							if (empty($mod) || $mod=='short')
								$prop='%X';
							return strftime($prop,$args[$pos]);
						default:
							return $expr[0];
					}
				return $args[$pos];
			},
			$val
		);
	}
560855
private function getFormattingTemplate($numberPattern, $numberFormat)
    {
        // Creates a phone number consisting only of the digit 9 that matches the
        // numberPattern by applying the pattern to the longestPhoneNumber string.
        $longestPhoneNumber = '999999999999999';
        $m = new Matcher($numberPattern, $longestPhoneNumber);
        $m->find();
        $aPhoneNumber = $m->group();
        // No formatting template can be created if the number of digits entered entered so far
        // is longer than the maximum the current formatting rule can accommodate.
        if (mb_strlen($aPhoneNumber) < mb_strlen($this->nationalNumber)) {
            return '';
        }
        // Formats the number according to $numberFormat
        $template = preg_replace('/' . $numberPattern . '/' . PhoneNumberUtil::REGEX_FLAGS, $numberFormat, $aPhoneNumber);
        // Replaces each digit with character self::$digitPlattern
        $template = preg_replace('/9/', self::$digitPattern, $template);
        return $template;
    }
294663
function format(f) {
  var i = 1;
  var args = arguments;
  var len = args.length;
  var str = String(f).replace(formatRegExp, function(x) {
    if (x === '%%') { return '%'; }
    if (i >= len) { return x; }
    switch (x) {
      case '%s':
        return String(args[i++]);
      case '%d':
        return Number(args[i++]);
      case '%j':
        return JSON.stringify(args[i++]);
      default:
        return x;
    }
  });
  return str;
}
766598
public function format($number, $currency_sign = NULL) {
    $this->symbol_replacements[self::SYMBOL_SPECIAL_CURRENCY] = $currency_sign;

    return parent::format($number);
  }
565548
def phone_number(random=random, *args, **kwargs):
    
    return random.choice([
        '555-{number}{other_number}{number}{other_number}',
        '1-604-555-{number}{other_number}{number}{other_number}',
        '864-70-555-{number}{other_number}{number}{other_number}',
        '867-5309'
    ]).format(number=number(random=random),
              other_number=number(random=random))