convert Persian/Arabic numbers to English numbers

PhpUnicode

Php Problem Overview


How can I convert Persian/Arabic numbers to English numbers with a simple function ?

Persian/Arabic numbers:

۰	//	-> 0
۱	//	-> 1
۲	//	-> 2
۳	//  -> 3
۴	//	-> 4
۵	//	-> 5
۶	//	-> 6
۷	//	-> 7
۸	//	-> 8
۹	//	-> 9

numbers over the unicode :

$num0="۰";
$num1="۱";
$num2="۲";
$num3="۳";
$num4="۴";
$num5="۵";
$num6="۶";
$num7="۷";
$num8="۸";
$num9="۹";

Php Solutions


Solution 1 - Php

Here's a short function:

function convert($string) {
    $persian = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
    $arabic = ['٩', '٨', '٧', '٦', '٥', '٤', '٣', '٢', '١','٠'];

    $num = range(0, 9);
    $convertedPersianNums = str_replace($persian, $num, $string);
    $englishNumbersOnly = str_replace($arabic, $num, $convertedPersianNums);
    
    return $englishNumbersOnly;
}

You can use the unicode instead of the characters in $persian (I think).

Solution 2 - Php

I use this function. It converts both Persian and Arabic digits to English:

function faTOen($string) {
	return strtr($string, array('۰'=>'0', '۱'=>'1', '۲'=>'2', '۳'=>'3', '۴'=>'4', '۵'=>'5', '۶'=>'6', '۷'=>'7', '۸'=>'8', '۹'=>'9', '٠'=>'0', '١'=>'1', '٢'=>'2', '٣'=>'3', '٤'=>'4', '٥'=>'5', '٦'=>'6', '٧'=>'7', '٨'=>'8', '٩'=>'9'));
}

sample:

echo faTOen("۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩"); // 01234567890123456789

Also you can convert English to Persian the same way:

function enToFa($string) {
	return strtr($string, array('0'=>'۰','1'=>'۱','2'=>'۲','3'=>'۳','4'=>'۴','5'=>'۵','6'=>'۶','7'=>'۷','8'=>'۸','9'=>'۹'));
}

Or English to Arabic:

function enToAr($string) {
	return strtr($string, array('0'=>'٠','1'=>'١','2'=>'٢','3'=>'٣','4'=>'٤','5'=>'٥','6'=>'٦','7'=>'٧','8'=>'٨','9'=>'٩'));
}

Solution 3 - Php

> Because people in the Persian & Arabic region maybe use each other keyboard types, this is the complete solution to convert both types.

Based on @palladium answer.

function convert2english($string) {
    $newNumbers = range(0, 9);
    // 1. Persian HTML decimal
    $persianDecimal = array('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹');
    // 2. Arabic HTML decimal
    $arabicDecimal = array('٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩');
    // 3. Arabic Numeric
    $arabic = array('٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩');
    // 4. Persian Numeric
    $persian = array('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹');

    $string =  str_replace($persianDecimal, $newNumbers, $string);
    $string =  str_replace($arabicDecimal, $newNumbers, $string);
    $string =  str_replace($arabic, $newNumbers, $string);
    return str_replace($persian, $newNumbers, $string);
}

Solution 4 - Php

this is better. we have two type of digits in arabic and persian. we must change all.

function convert($string) {
    $persinaDigits1= array('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹');
    $persinaDigits2= array('٩', '٨', '٧', '٦', '٥', '٤', '٣', '٢', '١', '٠');
    $allPersianDigits=array_merge($persinaDigits1, $persinaDigits2);
    $replaces = array('0','1','2','3','4','5','6','7','8','9','0','1','2','3','4','5','6','7','8','9');
    return str_replace($allPersianDigits, $replaces , $string);
}


thanks @Palladium

Be Careful when copying the code! Check twice how the array is presented in your editor or your will be in trouble!

Solution 5 - Php

$fmt = numfmt_create('fa', NumberFormatter::DECIMAL);
echo numfmt_parse($fmt, "۵") . "\n";
// 5

Solution 6 - Php

For convert all persian number to english format you can use this function:

function Convertnumber2english($srting) {
        
        $srting = str_replace('۰', '0', $srting);
        $srting = str_replace('۱', '1', $srting);
        $srting = str_replace('۲', '2', $srting);
        $srting = str_replace('۳', '3', $srting);
        $srting = str_replace('۴', '4', $srting);
        $srting = str_replace('۵', '5', $srting);
        $srting = str_replace('۶', '6', $srting);
        $srting = str_replace('۷', '7', $srting);
        $srting = str_replace('۸', '8', $srting);
        $srting = str_replace('۹', '9', $srting);
        
        return $srting;
    }

Solution 7 - Php

Two useful functions:

First convert to English number:

function convert_to_en_number($string) {
    $persian = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
    $arabic = ['٩', '٨', '٧', '٦', '٥', '٤', '٣', '٢', '١','٠'];

    $num = range(0, 9);
    $convertedPersianNums = str_replace($persian, $num, $string);
    $englishNumbersOnly = str_replace($arabic, $num, $convertedPersianNums);

    return $englishNumbersOnly;
}

Second convert to Persian number:

function convert_to_fa_number($string) {
    $num = range(0, 9);
    $arabic = ['٩', '٨', '٧', '٦', '٥', '٤', '٣', '٢', '١','٠'];
    $persian = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];

    $convertedEnglishNums = str_replace($num, $persian, $string);
    $persianNumbersOnly = str_replace($arabic, $persian, $convertedEnglishNums);

    return $persianNumbersOnly;
}

Solution 8 - Php

Very easy way to convert Arabic numbers to English number digits using below function:

function ArtoEnNumeric($string) {
    return strtr($string, array('۰'=>'0', '۱'=>'1', '۲'=>'2', '۳'=>'3', '۴'=>'4', '۵'=>'5', '۶'=>'6', '۷'=>'7', '۸'=>'8', '۹'=>'9', '٠'=>'0', '١'=>'1', '٢'=>'2', '٣'=>'3', '٤'=>'4', '٥'=>'5', '٦'=>'6', '٧'=>'7', '٨'=>'8', '٩'=>'9'));
}

echo ArtoEnNumeric('۶۰۶۳١۶۳٨'); 
Output = 60631638

Solution 9 - Php

I know this is a six-year old question, but I just came across this and developed a generic solution and I'd like to share it here for future readers.

Basically I use the NumberFormatter to generate the numbers in any foreign language, then I replace the numbers in the input string with the ones from English.

It should work for any language, but I wrote mine for Arabic.

/**
 * Replace Arabic numbers by English numbers in a string
 *
 * @param $value string A string containing Arabic numbers.
 * @param $source_language string The locale to convert chars from.
 *
 * @return string The string with Arabic numbers replaced by English numbers
 */
function englishifyNumbers ($value, $source_language = 'ar') {
    // Remove any direction overriding chars [LRO (U+202D)]
    $value = trim($value);

    // Create an Arabic number formatter to generate Arabic numbers
    $fmt = new \NumberFormatter(
        $source_language, 
        \NumberFormatter::PATTERN_DECIMAL
    );

    // Create an array of English numbers to use for replacement
    $english_numbers = range(0, 9);

    // Convert the English numbers to Arabic numbers using the formatter
    $arabic_numbers = array_map(function ($n) use ($fmt) {
        // Trim to remove direction overriding chars [PDF (U+202C)]
        return trim($fmt->format($n));
        
    }, $english_numbers);

    // Replace the numbers and return the result
    return str_replace($arabic_numbers, $english_numbers, $value);
}

Solution 10 - Php

$sting= '٩٨٥٤٠٣٧٦٣٢١'; 
  
// search stings
$seachstrings = array("١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩", "٠"); 
  
// replace strings 
$replacestrings= array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0"); 
  
// replace function 
$result= str_replace($seachstrings , $replacestrings, $sting); 
  
print_r($result); 

Solution 11 - Php

Probably a better answer using some kind of replace, but for coding it yourself, this would be better than what you have:

$len = strlen($arabic);
for ( $i = 0; $i < $len; ++$i )
{
    switch( $arabic[$i] )
    {
    case '&#1776':
        $english .= '0';
        break;
    case '&#1777':
        $english .= '1';
        break;
    case '&#1778':
        $english .= '2';
        break;
    // and so on
    case '&#1785':
        $english .= '9';
        break;
    default:
        $english .= $arabic[$i];
    }
}

That should do it.

Solution 12 - Php

how about something like this...

$number = arbic_to_english("&#1777;&#1779;");

echo $number; // 13

function arbic_to_english($number) {
	$english_number = 0;
	$matches = array();
	preg_match_all('/&#\d{4};/', $number, $matches);
	if(!count($matches) || !count($matches[0])) {
		throw new Exception('Invalid number');
	}
	$power = count($matches[0]) - 1;
	foreach($matches[0] as $arbic_digit) {
		$english_digit = preg_replace('/&#\d{2}(\d{2});/', '$1', $arbic_digit) - 76;
		$english_number += $english_digit * pow(10, $power--);
	}
	return $english_number;
}

Solution 13 - Php

No need to divide the input string.

private function convert($input)
{
    $unicode = array('۰', '۱', '۲', '۳', '٤', '٥', '٦', '۷', '۸', '۹');
    $english = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');

    $string = str_replace($unicode, $english , $input);

    return $string;
}

Examples

convert("۱۲۳٤٥");   //output : 12345

convert("۱۲34٥");   //output : 12345

convert("12345");   //output : 12345

Solution 14 - Php

the best way is to use NumberFormatter:

$formatter = \NumberFormatter::create('en', \NumberFormatter::DECIMAL);
echo $formatter->parse('۱۳۹۹'); // outputs: 1399

Solution 15 - Php

Here is a function that takes a string and zero of source language and zero of destination language

In below example I am converting numbers from Hindi to Latin for a given string

val = LangNum2Num("जिनसे आप कुछ ९० सीख सकते ३४ हैं हम लाये हैं ७ आपके लिये कुछ", "०", 0)
console.log(val)
// Prints जिनसे आप कुछ 90 सीख सकते 34 हैं हम लाये हैं 7 आपके लिये कुछ




// Coverts numbers insides a string to other language number
// str is the string
// zeroFrom is the zero number from the language you want to convert
// zeroTo is the zero number of the languague you want to convert to

function LangNum2Num(str, zeroFrom, zeroTo) {
  // Get the UTF-16 code points of zeros
  codezeroFrom = ("" + zeroFrom).codePointAt(0)
  codezeroTo = ("" + zeroTo).codePointAt(0)

  // Make array containing codepoints from 0 to 10 for the language
  var FromArr = [...Array(10).keys()].map(e => codezeroFrom + e)
  var ToArr = [...Array(10).keys()].map(e => codezeroTo + e)

  // Split the string into array, if we catch a number, we will return number from destination language
  return str.split('').map(e => FromArr.includes(e.codePointAt(0)) ? String.fromCodePoint(ToArr[FromArr.indexOf(e.codePointAt(0))]) : e).join('')

}

Solution 16 - Php

I used this function

function toEngNumbers($string)
{
    $arabic = ['٩', '٨', '٧', '٦', '٥', '٤', '٣', '٢', '١', '٠'];
    $persian = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
    $english = ['9', '8', '7', '6', '5', '4', '3', '2', '1', '0'];

    $convertedPersianNums = str_replace($persian, $english, $string);
    $converted = str_replace($arabic, $english, $convertedPersianNums);
    return $converted;
}

Solution 17 - Php

Based on @Root answer:

function to_english_number( $string ) {

	$persianDecimal = [ '&#1776;', '&#1777;', '&#1778;', '&#1779;', '&#1780;', '&#1781;', '&#1782;', '&#1783;', '&#1784;', '&#1785;' ];
	$arabicDecimal  = [ '&#1632;', '&#1633;', '&#1634;', '&#1635;', '&#1636;', '&#1637;', '&#1638;', '&#1639;', '&#1640;', '&#1641;' ];

	$persian = [ '۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹' ];
	$arabic  = [ '٩', '٨', '٧', '٦', '٥', '٤', '٣', '٢', '١', '٠' ];

	$num = range( 0, 9 );

	$string = str_replace( $persianDecimal, $num, $string );
	$string = str_replace( $arabicDecimal, $num, $string );

	$string = str_replace( $persian, $num, $string );
	$string = str_replace( $arabic, $num, $string );

	return $string;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRootView Question on Stackoverflow
Solution 1 - PhpPalladiumView Answer on Stackoverflow
Solution 2 - PhpSaeid TahmuresiView Answer on Stackoverflow
Solution 3 - PhpRootView Answer on Stackoverflow
Solution 4 - PhpimanView Answer on Stackoverflow
Solution 5 - PhpIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 6 - PhpMorteza Sepehri NiyaView Answer on Stackoverflow
Solution 7 - PhpAli MotameniView Answer on Stackoverflow
Solution 8 - PhpAditya P BhattView Answer on Stackoverflow
Solution 9 - PhpiSWORDView Answer on Stackoverflow
Solution 10 - PhpInba SekarView Answer on Stackoverflow
Solution 11 - PhpKRyanView Answer on Stackoverflow
Solution 12 - PhphackattackView Answer on Stackoverflow
Solution 13 - PhpMohamed ElorbanyView Answer on Stackoverflow
Solution 14 - PhpPezhvakView Answer on Stackoverflow
Solution 15 - PhpFawaz AhmedView Answer on Stackoverflow
Solution 16 - PhpMansour AlnasserView Answer on Stackoverflow
Solution 17 - PhpMahdi AkramiView Answer on Stackoverflow