Add commas as thousands delimiter in Arabic money number expression

338 Views Asked by At

i am looking for a regular expression to insert commas into a numbers. For example, I have 999999999 and I want to insert a thousand separator.

I know I can use number_format(), but that doesn't solve my problem since my digits are actually in Arabic format ۱۲۳۴۵۶۷۸۹۰.

Maybe there is a regular expression to insert a character after certain number of characters in a string.

I tried using preg_replace(), but couldn't find the answer.

I found the below code from one of the answers on stackoverflow but it throws error:

$num = '۱۲۳۴۵۶۷۸۹۰';
$n = preg_replace(/([۱۲۳۴۵۶۷۸۹۰])/,(?=(?:[۱۲۳۴۵۶۷۸۹۰]{3})+$),$num);
echo $n;
3

There are 3 best solutions below

0
Clément Baconnier On BEST ANSWER

Based on @JellyBean answer

$num = '۱۲۳۴۵۶۷۸۹۰';
$newNum = wordwrap($num , 6 , ',' , true );

This will echo out ۱۲۳,۴۵۶,۷۸۹,۰

First of, why 6? Because The chars uses 2 bytes. Second, there's still a problem; What we want is this: ۱,۲۳۴,۵۶۷,۸۹۰

Solution

We can reverse it

$num = strrev('۱۲۳۴۵۶۷۸۹۰');
$newNum = strrev(wordwrap($num , 6 , ',' , true ));

echo $newNum;

۱,۲۳۴,۵۶۷,۸۹۰

POC: https://3v4l.org/OVeQQ

1
Jelly Bean On

Try using wordwrap

$num = '۱۲۳۴۵۶۷۸۹۰';
$newNum = wordwrap($num , 4 , ',' , true );

this should output: '۱۲۳۴,۵۶۷۸۹۰'

source: PHP.net wordwrap

1
yovie On

Try this :

$num = '۱۲۳۴۵۶۷۸۹۰';
$ar = str_split($num, 3);
$result = implode(',', $ar);
echo $result;