phpregexstringnumber-formatting

convert a string to persian number format


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;

}

Solution

  • As converting to Persian is a just character replacing, you can format number using built-in number_format() function and then replace characters in the result as needed:

    function trans($num)
        {
            $persian_array = [
                '0'=>'۰',
                '1'=>'۱',
                '2'=>'۲',
                '3'=>'۳',
                '4'=>'۴',
                '5'=>'۵',
                '6'=>'۶',
                '7'=>'۷',
                '8'=>'۸',
                '9'=>'۹',
                ','=>'٬', // Persian/Farsi and Arabic thousands separator
                '.'=>'٫'  // Persian/Farsi and Arabic decimal separator
            ];
            $num = (float) $num;
            return strtr(number_format($num), $persian_array);
        }
        
    echo trans(1125120124); // ۱٬۱۲۵٬۱۲۰٬۱۲۴