开发者

To get Numeric value from a alphanumeric String in PHP?

i want a function or a code to get numeric value from the string whose value is "2008 R开发者_运维技巧evenue $5,700,390,000". the output that i want is $5,700,390,000.


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


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

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜