1
4

2 回答 2

0

您可以尝试运行类似这样的正则表达式(未经测试):

if(preg_match('/([$€])([\d\.]+)\s?([\w]+)[^\(]*\((\d+)\)/',$value,$matches)){
    switch($matches[1]){
        case '$':
            $currency = 'dollar';
            break;
        case '€':
            $currency = 'euro';
            break;
        // and more for more currencies
    }
    $number = $matches[2];
    switch($matches[3]){
        case 'billion':
            $number = intval($number*1000000000);
            break;
        case 'million':
            $number = intval($number*1000000);
            break;
        // and more for more multipliers
    }
    $year = $matches[4];
}

请记住在正则表达式的第一对方括号中添加您需要支持的所有可能的货币符号[$€]

于 2012-12-27T18:55:30.690 回答
0

未经测试,我相信有更优雅的方式来做事,但这应该有效:

<?php

echo parseCurrency('$6.041 billion USD (2006)');


function parseCurrency($input){
 if(strpos($input, 'USD') || strpos($input, '$')){
     $currency = 'USD';
     $floatVal = (float) get_string($input, '$', ' ');
 }
 elseif(strpos($input, '€')){
     $currency = 'EUR';
     $floatVal = (float) get_string($input, '€', ' ');
 }
 else{
     $currency = 'undefined';
     die();
 }

 if(strpos($input, 'billion'){
    $number = $floatVal * 1000000000;
 } 
 elseif(strpos($input, 'million'){
    $number = $floatVal * 1000000;
 }
 else{
    $number = 'undefined';
    die();
 }
 if (preg_match('/\\([12][0-9]{3}\\)/', $input, $years)){
    $year = $years[0];
 }
 else{
    $year = 'undefined';
    die();
 }
 return $number . ', ' . $currency . ', ' . $year;
}

//used to find million or billion
function get_string($string, $start, $end){
 $string = " ".$string;
 $pos = strpos($string,$start);
 if ($pos == 0) return "";
 $pos += strlen($start);
 $len = strpos($string,$end,$pos) - $pos;
 return substr($string,$pos,$len);
}
于 2012-12-27T18:56:14.177 回答