2012-11-20 80 views
3

我寫了下面的代碼工作,但它的工作原理錯誤:str_replace函數不對某些字符

$t = "۰۱۲۳۴۵۶۷۸۹٤٥٦"; 
$correct = array("0","1","2","3","4","5","6","7","8","9","4","5","6"); 
$wrong = array("٠","١","٢","٣","٤","٥","٦","٧","٨","٩","۴","۵","۶"); 
echo $t = str_replace($wrong,$correct, $t); 

,結果是不正確的

۰۱۲۳456۷۸۹۰۱۲۳456۷۸۹456 

我在堆棧和相同的問題,搜索和它的答案不幫助我。

回答

1

我不`噸知道任何關於這個問題,但你可以試試這個功能來實現的想法:

//converts the numbers into the persian's number 
function persianNum($srting) 
{ 
    $num0="۰"; 
    $num1="۱"; 
    $num2="۲"; 
    $num3="۳"; 
    $num4="۴"; 
    $num5="۵"; 
    $num6="۶"; 
    $num7="۷"; 
    $num8="۸"; 
    $num9="۹"; 

    $stringtemp=""; 
    $len=strlen($srting); 
    for($sub=0;$sub<$len;$sub++) 
    { 
     if(substr($srting,$sub,1)=="0")$stringtemp.=$num0; 
     elseif(substr($srting,$sub,1)=="1")$stringtemp.=$num1; 
     elseif(substr($srting,$sub,1)=="2")$stringtemp.=$num2; 
     elseif(substr($srting,$sub,1)=="3")$stringtemp.=$num3; 
     elseif(substr($srting,$sub,1)=="4")$stringtemp.=$num4; 
     elseif(substr($srting,$sub,1)=="5")$stringtemp.=$num5; 
     elseif(substr($srting,$sub,1)=="6")$stringtemp.=$num6; 
     elseif(substr($srting,$sub,1)=="7")$stringtemp.=$num7; 
     elseif(substr($srting,$sub,1)=="8")$stringtemp.=$num8; 
     elseif(substr($srting,$sub,1)=="9")$stringtemp.=$num9; 
     else $stringtemp.=substr($srting,$sub,1); 
    } 
return $stringtemp; 

} 
//end convert function 
+0

這段代碼很慢。每個if語句都會運行'substr()'函數,當有一個很長的for循環和這麼多'substr'函數時,你的代碼將會非常慢!如果你想使用這種方法,最好有一個開關(http://nl3.php.net/manual/en/control-structures.switch.php)。這又是,不建議。儘管我不會低估它,因爲它有幫助,但也不是那麼好。 – Jelmer

+0

是的,你是對的!代碼太重且太慢,但它是面對一段替代HTML代碼時最靈活的代碼。 –

+0

我想將它與其相反,我想將波斯語數字轉換爲拉丁語,所以我將它更改爲'if (substr($ srting,$ sub,2)==「$ num8」)$ stringtemp。= 8;'因爲unicodes得到2字節 – Ehsan

2

使用此代碼: -

$t = "۰۱۲۳٤٥٦"; 
$text = preg_replace(
      array("٠","١","٢","٣","٤","٥","٦",), 
      array("0","1","2","3","4","5","6",), 
      $t); 
0

在PHP中沒有mb_str_repalce函數。此代碼將字符串中的字符從東方阿拉伯數字轉換爲印度 - 阿拉伯數字:

<?php 
function arabic_convert($str = ''){ 
    $str_list = preg_split('//u', $str, null, PREG_SPLIT_NO_EMPTY); 

    if(!empty($str_list)){ 
     $transform_symbols = array(
      '٠' => '0', 
      '١' => '1', 
      '٢' => '2', 
      '٣' => '3', 
      '٤' => '4', 
      '٥' => '5', 
      '٦' => '6', 
      '٧' => '7', 
      '٨' => '8', 
      '٩' => '9', 
     ); 

     $str_transform = array(); 

     foreach ($str_list as $str_item){ 
      if(isset($transform_symbols[$str_item])){ 
       $str_transform[] = $transform_symbols[$str_item]; 
      }else{ 
       $str_transform[] = $str_item; 
      } 
     } 

     $str = implode('', $str_transform); 
    } 

    return $str; 
} 
+0

請解釋爲什麼這段代碼有助於OP的問題。 –

+0

在PHP中沒有mb_str_repalce函數。此代碼將字符串中的字符從東方阿拉伯數字轉換爲印度阿拉伯數字 – Anton

+0

編輯您的答案以包含該信息。 –