Q:

Write a PHP program to sum of all numerical values (positive integers) embedded in a sentence

0

Write a PHP program to sum of all numerical values (positive integers) embedded in a sentence.
Sentences with positive integers are given over multiple lines. Each line is a character string containing one-byte alphanumeric characters, symbols, spaces, or an empty line. However the input is 80 characters or less per line and the sum is 10,000 or less.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

<?php
$sum = 0;
    $s = rtrim(fgets(STDIN));
    if (preg_match_all('/[0-9]+/', $s, $a)) {
        foreach ($a[0] as $v) {
            $sum += (int) $v;
        }
    }
echo "Sum of the numeric values: ".$sum . PHP_EOL;
?>

Sample Input:
5 apple and 10 orange are rotten in the basket

Sample Output:

Sum of the numeric values: 15

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now