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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.