Jump to content

Adding Values in a string


mme

Recommended Posts

Hi,

 

I currently have a string with some values in it:

 

$a_random_string="some random text, goes here - $123<br>some more random text goes here - $53 (text 123 )<br>ANother line of text - $126";

 

Now I want to add all the values that have a '$' before the value eg; $123.

 

So in this case I would end up with: 302

 

How would I do this?

 

Thanks,

 

mme

Link to comment
https://forums.phpfreaks.com/topic/215022-adding-values-in-a-string/
Share on other sites

Thank you for your reply,

 

Basically I have a string of variable data in it and I want to add up all the numeric values in the string that have the $ character in front of the number. However I do not want the numbers with the $ character before the number to be added.

 

eg;

 

blabla 621.

- Dont include this

 

more text $63. with some more text 12.

- Include the number 63 but not the number 12

 

Hope that helps.

 

Thanks,

 

mme

Hey mme, have a look at the following...

 

<?php
  // String to get values from
  $startString = 'some random text, goes here - $123<br>some more random text goes here - $53 (text 123 )<br>ANother line of text - $126';
  // Add | to all values that begin with $ and contain numbers
  $string = preg_replace('/(\$[0-9]{1,})/','|$1|',$startString);
  // Explode |
  $string = explode('|',$string);
  // Count Length of exploded string
  $count  = count($string);

  // Preg match for any values not contain a space
  // If no space is found, it must be a number beginning with $
  // Replace $ and then add the values up
  for($i=0; $i<$count; $i++) {
    if(!preg_match("/ /i", $string[$i])) {
      $result += str_replace('$','',$string[$i]);
    }
  }

  // Echo resulting value
  echo $result;
?>

 

Tell me if it works out for you bud :)

 

Regards, Paul.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.