duanshang3230 2013-03-30 20:00 采纳率: 100%
浏览 20
已采纳

用数字替换替换字符串中的数字

lets say i have those two arrays

   $letters = array('a','b','c', 'd', 'e');
   $replace = array( 1,  5,  10, 15 , 20);
   $text = "abd cde dee ae d" ;
   $re = str_replace($letters, $replace, $text) ;
   echo $re ;  //this output:

     1515 101520 152020 120 15 

Now i want sum the above numbers for each word and the result should be like that:

     21 45 55 21 15

what i tried is :

    $resultArray = explode(" ", $re); 

    echo array_sum($resultArray).'<br />' ; // but it output wrong result. 
                                           // it output this : 255190

how can i achieve this ?

any help much apreciated.

EDIT:

with arabic letters like that

   $letters = array('ا', 'ب','ج','د' ) ;
   $replace = array(1, 5, 10, 15 ) ;
   $text = "جا باب جب"; 
  • 写回答

2条回答 默认 最新

  • dongshu4755 2013-03-30 20:03
    关注

    Convert the string into an array and use array_sum.

    array_sum(explode(' ', $re));
    

    Edit

    Sorry, misunderstood:

    $letters = array('a','b','c', 'd', 'e');
    
    $replace = array( 1,  5,  10, 15 , 20);
    
    $text = "abd cde dee ae d" ;
    
    $new_array = explode(' ', $text);
    
    $sum_array = array();
    
    foreach ($new_array as $string)
    {
    
      $nums = str_split($string);
    
      foreach ($nums as &$num)
      {
        $num = str_replace($letters, $replace, $num);
      }
    
      $sum_array[] = array_sum($nums);
    
    }
    
    echo implode(' ', $sum_array);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料