3
\$\begingroup\$

I'm using this function to replace UTF-8 characters representing numbers in text with 'normal' digits.

I'm wondering if this is optimized code since this is using two str_replace()s.

public static function convertArabicNumbers($string) {
    //$engish = array(0,1,2,3,4,5,6,7,8,9);
    $persian = array('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹');
    $arabic = array('٠','١','٢','٣','٤','٥','٦','٧','٨','٩');
    $num = range(0, 9);
    return str_replace($arabic, $num, str_replace($persian, $num, $string));
}
\$\endgroup\$
3
\$\begingroup\$

You are right that this is not optimal (performance wise). You may want to consider two things:

  1. static variables (those values in there are constants no need to recreate them every time).
  2. merging the arrays.

Consider the following code:

public static function convertArabicNumbers($string) {
    //$engish = array(0,1,2,3,4,5,6,7,8,9);
    static $fromchar = array('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹',
                             '٠','١','٢','٣','٤','٥','٦','٧','٨','٩');
    static $num = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
    return str_replace($fromchar, $num, $string);
}

I am really uncertain about the right-to-left characters.... should they be transformed in the same way as the left-to-right ones? You're the expert on that one.

Still, you get the idea....

\$\endgroup\$
  • 1
    \$\begingroup\$ thank you I think you are right, btw both languages are left to right in numbers though \$\endgroup\$ – Developerium May 7 '14 at 11:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.