How can I identify the currency symbol in a string that has both symbol and value in?
I'm getting data into a script via XML (not important)... Part of the data is a value amount that includes the currency symbol and the amount, for example:
["price"]=> string(6) "$65.00"
["price"]=> string(8) "€14.20"
Now, I'm looking for a way to automatically work out which bit is the currency symbol and which bit is the value. I can't guarrantee the quality of data coming in, for example the amount could be £14,000.22 or the symbol may be not just a single letter - ie Swiss Francs - CHF.
Can anyone point me in the right direction? I tried this code which worked for the dollar symbol but not the euro symbol:
if (preg_match('/\p{Sc}/',trim($price),$matches)) {
var_dump($matches);
}
output
array(1) {
[0]=>
string(1) "$"
}
For referenc开发者_开发问答e I looked at http://www.xe.com/symbols.php for a list of the worlds currency symbols.
I am not sure what the exact source data you are dealing with. However, in accounting, there are different formats for different currencies. For example some currencies would prefix their currency symbol. Others would suffix the symbol. Depending on the language of the currency, you might also have different symbols for decimal.
/^(\D*)\s*([\d,\.]+)\s*(\D*)$/
The above regular expression (JavaScript flavor, you might need to escape it to convert it into PHP), would match the following:
- €14,20
- $65.00
- 65.00USD
The following will give you the amount in $matches[2]
, and the currency symbol or alpha representation will always be in $matches[1]
or $matches[3]
respectively.
$values = array("$5.00", "€1.23", "£1,323.45", "1.23USD");
foreach($values as $val)
{
preg_match("/([^0-9.,]*)([0-9.,]*)([^0-9.,]*)/", $val, $matches);
print_r($matches);
}
Perhaps using sscanf() rather than a preg function
$price = "$65.00";
list($symbol, $price) = sscanf($price,'%[^0-9]%s');
var_dump($symbol);
var_dump($price);
$price= "€14.20";
list($symbol, $price) = sscanf($price,'%[^0-9]%s');
var_dump($symbol);
var_dump($price);
$price= "CHF1,357.99";
list($symbol, $price) = sscanf($price,'%[^0-9]%s');
var_dump($symbol);
var_dump($price);
Following simple regular expression might help
price
grep -o '[0-9.,]*'
Symbol
grep -o '[^0-9.,]*'
I would use Number Format in PHP 5.
Requirements:
- (PHP 5 >= 5.3.0, PECL intl >= 1.0.0)
Sample Code:
$Format = new NumberFormatter("en", NumberFormatter::TYPE_DOUBLE);
echo $Format->format("$1928.77");
Homepage: http://www.php.net/manual/en/class.numberformatter.php
精彩评论