-1

I have a string like this

aaa ~120 Sek. 53 Sek. ~~ bbb asdfasf aasdf asdfasdf ~600 Sek.~~ ccc ~60 Sek. 43 Sek. ~~ ddd ~240 Sek. 55 Sek. ~~

I have to add up all the xxx Sek. (which are just seconds).

Any good idea?

Regards Bruno

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
dh1sbg
  • 15
  • 5
  • Just added the regex tag as this may be a useful way of doing this. – Nigel Ren Mar 31 '20 at 10:13
  • _“Any good idea?”_ - please go read [ask]. We expect you to put a bit more initial effort into your problem/question here, than just asking us for “ideas”. – CBroe Mar 31 '20 at 11:08

1 Answers1

3

One way to do with regex look ahead, so you can get all the digits followed by Sek word. If you want to do any filtering on a matched result like 3 digits or something else then you can use strlen() function.

$re = '/\d+(?= Sek)/';
$str = 'aaa ~120 Sek. 53 Sek. ~~ bbb asdfasf aasdf asdfasdf ~600 Sek. ~~ ccc ~60 Sek. 43 Sek. ~~ ddd ~240 Sek. 55 Sek. ~~';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

// Print the entire match result
#print_r($matches);
$sum = 0;
foreach ($matches as $item) {
    $sum += $item[0];
}
echo $sum;

Edit: Calculate sum alternatively,

$sum = array_reduce($matches, function(&$result, $item) {
    return $result + $item[0];
}, 0);

OR

$sum= array_sum(array_column($matches,0));

Working demo: https://3v4l.org/iQp0q

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
  • It works - if I work with the $str (like above) when I hardcode this string $str. As soon as I enter the same string to a MySql database and retrieve it from there: The result does not work, The sum will use only 53+43. It doesn't care about 120, 600 and 60. – dh1sbg Apr 03 '20 at 11:34
  • For all field -contents from mysql: I replaced ÄÖÜßäöü with ä Now my code works fine. – dh1sbg Apr 03 '20 at 13:15
  • @dh1sbg glad it works now, https://stackoverflow.com/help/someone-answers – A l w a y s S u n n y Apr 03 '20 at 13:18