too long

I'm trying to write function to do the number_format() job for the non-ascii numbers , specifically perso-arabic numbers.

First i have to exchange the numbers which leaves me with a string of non-ascii characters:

$n = 133;
$n = exchange($n);
echo $n ;
//result : ١٣٣

The problem is when I add the commas to the number or rather string, my final result comes with some � characters.

Here is the function that I use to add the commas:

    static public function addcomma($number)
       {

    $i = strlen($number)-1;
    $c = 0 ;

    for($i ; $i >= 0 ; $i--){
    $c++;

    if($c == 1 ) 
    $y =mb_substr($number, $i, 1);
    else 
    $y .= mb_substr($number, $i, 1);



    if($c%3 == 0 && $i != 0 )
    $y .=',';
    }
    $y = strrev($y);
    return $y;

    }

And this is the result for $n = ١٣٣:

٣,٣�,�١

Some of your characters (likely all) are stored on more than one byte, unline regular ASCII strings. So you have to use multibyte string functions to manipulate the strings. You can't use strlen, substr and strrev (or any other regular string function), and you can't just treat the string as an array. So, you have to change some sections of your code, like this:

$i = mb_strlen($number)-1;
// (...)
$y = mb_substr($number, $i, 1);

There is no multibyte equivalent for strrev, so you can try this (suggested on a comment at the strrev manual page):

// strrev won't work
// $y = strrev($y); 
$y = join("", array_reverse(preg_split("//u", $y)));

The above will split the string into an array, respecting the multibyte boundaries (note the u at the end of the regex), reverse that array, and then join it back to a string.

Your arabic string (ie, whatever you get from exchange()) is very likely encoded in UTF-8, or basically some non 8-bit format. As soon as you begin twiddling with the string as an array (which PHP assumes is 8-bit), you break the UTF-8 string and it comes out with those funny question marks when it's printed to the screen (which by the way, ensure your document encoding type is set to UTF-8 as well).

Depending on the version of PHP, you'll need to use mb_string functions to fiddle with multi-byte strings, which is what you have.