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;
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: ۱,۲۳۴,۵۶۷,۸۹۰
We can reverse it
$num = strrev('۱۲۳۴۵۶۷۸۹۰');
$newNum = strrev(wordwrap($num , 6 , ',' , true ));
echo $newNum;
۱,۲۳۴,۵۶۷,۸۹۰