Home > other >  Extract numbers from string and add them with php
Extract numbers from string and add them with php

Time:07-12

I have a long string like below:

$string = "age1:32,age2:25,age3:52,..."

Now I want to extract the age numbers in this string and then add the numbers together and determine the average age. I was able to extract the numbers with the help of the following code

$numbers = preg_replace('/[^0-9]/', '', $string );

but the output I get is like this and I cannot add the numbers together.

output: 322552

CodePudding user response:

Using preg_match_all to find all age values followed by array_sum to find the total/average we can try:

$string = "age1:32,age2:25,age3:52,...";
preg_match_all("/age\d :(\d )/", $string, $matches);
print_r(array_sum($matches[1]) / count($matches[1]));  // 36.333333333333

CodePudding user response:

  1. Restart the fullstring match after each colon, then match one or more digits.
  2. preg_match_all() returns the number of matches ($count).
  3. Divide the sum of the matches by the number of matches.

Code: (Demo)

$string = "age1:32,age2:25,age3:52,...";
$count = preg_match_all('/:\K\d /', $string, $m);
echo array_sum($m[0] ?? []) / $count;
// 36.333333333333

If you wanted to grab all numbers, just use \d . (Demo)

$string = "available12available15available22available11...";
$count = preg_match_all('/\d /', $string, $m);
echo array_sum($m[0] ?? []) / $count;
  •  Tags:  
  • php
  • Related