I have a number string in Persian numbers for example
۱۱۲۵۱۲۰۱۲۴
which is 1125120124 in English numerical. I want to convert this string to number format separated by commas after every thousand for example
۱,۱۲۵,۱۲۰,۱۲۴
like when I do
number_format(1125120124); // it returns as 1,125,120,124
and
number_format(112512012); // it returns as 112,512,012
So actualy I want similar results as of number_format method. I just started regular expressions. Tried with very basic patterns but still no where near. Tried preg_split to split string and concatenate it again with commas but does not seem to be right approach. I have a function where I pass a number that returns me that number in Persian characters. Sharing that too
function trans($num)
{
$persian_num_array = [
'0'=>'۰',
'1'=>'۱',
'2'=>'۲',
'3'=>'۳',
'4'=>'۴',
'5'=>'۵',
'6'=>'۶',
'7'=>'۷',
'8'=>'۸',
'9'=>'۹',
];
$translated_num = '';
$temp_array=[];
while ($num > 0) {
array_push($temp_array,$num % 10);
$num = intval($num / 10);
}
foreach($temp_array as $val){
$translated_num.= $persian_num_array[array_pop($temp_array)];
}
echo $translated_num;
}
As converting to Persian is a just character replacing, you can format number using built-in number_format() function and then replace numbers without replacing commas. Here is an example:
function trans($num)
{
$persian_num_array = [
'0'=>'۰',
'1'=>'۱',
'2'=>'۲',
'3'=>'۳',
'4'=>'۴',
'5'=>'۵',
'6'=>'۶',
'7'=>'۷',
'8'=>'۸',
'9'=>'۹',
];
$num = (float) $num;
return strtr(number_format($num), $persian_num_array);
}
echo trans(1125120124); // returns ۱,۱۲۵,۱۲۰,۱۲۴
PHP's Intl extension includes a NumberFormatter class that can format your number for a given locale.
$number = "1125120124";
$formatter = NumberFormatter::create("fa_IR", NumberFormatter::DEFAULT_STYLE);
echo $formatter->format($number);
۱٬۱۲۵٬۱۲۰٬۱۲۴
To force a comma to be used, it has a setSymbol()
method.
$number = "1125120124";
$formatter = NumberFormatter::create("fa_IR", NumberFormatter::DEFAULT_STYLE);
$formatter->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, ",");
echo $formatter->format($number);
۱,۱۲۵,۱۲۰,۱۲۴
Or if your input was in Persian, first use a Transliterator on it.
$input = "۱۱۲۵۱۲۰۱۲۴";
$transliterator = Transliterator::create("fa-fa_Latn/BGN");
$number = $transliterator->transliterate($input);
echo $number, "
";
$formatter = NumberFormatter::create("fa_IR", NumberFormatter::DEFAULT_STYLE);
$formatter->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, ",");
echo $formatter->format($number);
1125120124
۱,۱۲۵,۱۲۰,۱۲۴