HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Replacing Perisan and Arabic digits

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
digitsperisanreplacingandarabic

Problem

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));
}

Solution

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

  • static variables (those values in there are constants no need to recreate them every time).



  • 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....

Code Snippets

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);
}

Context

StackExchange Code Review Q#49138, answer score: 3

Revisions (0)

No revisions yet.