Adding up Totals from a string

Hi,

I was wondering how this can be done in PHP:

Input:

[php]$something = “some text - $113.80

another line of text - $200

yet another one - $45”;[/php]

Output:

[php]358.80[/php]

Adding all the values contained within the text (starting with an $ symbol)

How would I do this?

Thanks,

Dennis

Hi are you looking for a function that would work in any situation involving text and numbers?

Or would it always be in that same form/layout/pattern?

First, you’ll need to extract $ amounts from the string. This can easily be done with regular expressions:

[php]<?php
if(preg_match_all(’~$([0-9.]+)~’,$something,$matches)){
// some amounts found - sum them and display
echo array_sum($matches[1]);
}
?>[/php]

Sponsor our Newsletter | Privacy Policy | Terms of Service