Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 和数组数_Php_Sum - Fatal编程技术网

Php 和数组数

Php 和数组数,php,sum,Php,Sum,这是我的代码: $letters = array('a','b','c', 'd', 'e'); $replace = array( 1, 5, 10, 15 , 20); $text = "abd cde dee ae d" ; $res = array_sum(str_split(str_replace($letters, $replace, $text))) ; echo $res ; // this output: 40 它应该输出:157 这意味

这是我的代码:

   $letters = array('a','b','c', 'd', 'e');
   $replace = array( 1,  5,  10, 15 , 20);
   $text = "abd cde dee ae d" ;
   $res = array_sum(str_split(str_replace($letters, $replace, $text))) ;

  echo $res ; // this output:   40
它应该输出:
157

这意味着当我用数字替换字母时,我会用
array\u sum

怎么了

编辑:

str_split()
按字母拆分,但如果在之后用数字替换字母,则应用。这意味着,例如,“20”将被分为“2”和“0”


您可能需要先拆分,然后在
array_map()

的帮助下替换字母。请看,这里发生的情况是字符串中的每个字符都被拆分,即
15
,对
d
的替换将被拆分为
1
5
。分别地相反,请尝试以下方法:

$replace = array( '1 ',  '5 ',  '10 ', '15 ' , '20 ');
$letters = array('a','b','c', 'd', 'e');
$text = "abd cde dee ae d" ;
$res = array_sum(explode(' ', str_replace($letters, $replace, $text))) ;
echo $res ;
这里发生的是
explode()
在给定的分隔符(这里是空格字符)处拆分字符串。看

用阿拉伯语字母试试这个

   function mb_str_split( $string ) {
     return preg_split('/(?<!^)(?!$)/u', $string );
     } 
   $res = array_sum(str_replace($letters, $replace,mb_str_split( $text))) ;
函数mb_str_split($string){

return preg_split('/(?你昨天问过它:D,我猜这是你要求它的行为!它不一样,昨天是数组中的和,但这个总和在这里如果你想看看它是否相同@PolishPrince它没有重复,我知道我问什么为什么应该是157?你能证明吗?很好:)谢谢,我的错是分裂:)对多字节字符集(如阿拉伯语)使用
mb_split()
,而不是
explode()
。只需将
explode()
替换为
mb_split()
。看,我编辑了你的答案,如果你敢的话,我修正了它。谢谢沙哈,同时建议了一种类似的方法:)谢谢:),我不知道为什么对我投反对票:)谢谢,非常感谢你的回答你能用数组图解释一下你的方法吗?
   function mb_str_split( $string ) {
     return preg_split('/(?<!^)(?!$)/u', $string );
     } 
   $res = array_sum(str_replace($letters, $replace,mb_str_split( $text))) ;