views:

88

answers:

4

i want a function or a code to get numeric value from the string whose value is "2008 Revenue $5,700,390,000". the output that i want is $5,700,390,000.

A: 

This may be a good use of regular expressions (how to with PHP).

The expression \$[\d,]+ seems to work.

C. Ross
+2  A: 

If you're absolutely certain the string will always be formatted as YEAR TYPE VALUE with spacings between the values you could:

$str = "2008 Revenue $5,700,390,000";

$exploded = explode(" ", $str);

$my_value = $exploded[2];
matiasf
That would still be a string: "$5,700,390,000" - so a call to floatval or intval on that value would still be needed.
Sohnee
thanks Matiasf, yeah the format is the same.
Harish Kurup
In addition to matiasf's solution, there are many ways this can be done simply with php's string functions. For instance: my_value = strrchr($str, '$');
GZipp
A: 

I only know C#, but I would use a Regex, like [\$.0-9]+ in its simplest form. If you need culture awareness (e.g. different currency symbols) you need to add more logic. Hope this helps.

John
A: 

This is a hybrid using the built-in "floatval()" function and a regular expression - this deals with more complex strings.

function floatvalue($value) {
     return floatval(preg_replace('#^([-]*[0-9\.,\' ]+?)((\.|,){1}([0-9-]{1,2}))*$#e', "str_replace(array('.', ',', \"'\", ' '), '', '\\1') . '.\\4'", $value));
} 

If you have more simple situations "32121.54BLAH" for example, floatval() will handle these without assistance.

Sohnee