How to sum of all numeric values in a string with PHP

1 Answer

0 votes
$s = "1 php 10 java 9 c 13";

$sum = 0;
if (preg_match_all('/[0-9]+/', $s, $arr)) {
    foreach ($arr[0] as $val) {
        $sum += (int)$val;
    }
}
echo $sum;


/*
run:

33
 
*/

 



answered Feb 28, 2019 by avibootz
...