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
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
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